From fbcebd088c205070e9bae22821b2a2e8920a07c5 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:13:25 -0500 Subject: [PATCH 01/16] 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 bbdb45f5..ee13305c 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 696a08a7..0d3e7a0c 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 02/16] 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 b9413e51..f7318ec4 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 2542016e..7c944b5c 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 03/16] 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 08411eb7..cfd74bf3 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 1b6b9efb..a3788179 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 04/16] 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 708007d0..5f66ab60 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 500d6a12..ecb024af 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 05/16] 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 d2424440..1985d86b 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 f0ed3cb4..cd020c14 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 06/16] 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 0ae9da78..6e64157c 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 b00e2f23..0d6deebd 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 07/16] 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 c769fb49..9c4d6401 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 ee6bc39b..c71e6f2a --- 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 08/16] 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 9d551425..e0bd5f16 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 25ab220d..36af23b0 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 09/16] 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 a9c0826d..bf19efa9 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 10/16] 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 e9119ff7..cf383347 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 c05763a0..08b5190d 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 11/16] 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 cf383347..5b0fa08d 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 08b5190d..229daad3 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 12/16] 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 ee13305c..93936225 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 f7318ec4..8e268cf1 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 13/16] 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 8e268cf1..027b9b3a 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 14/16] 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 3b4781f2..b500bbee 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 1d4672ff..98d739c9 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 09a62b2a..cd872b28 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 15/16] 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 b500bbee..de99fb6c 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 98d739c9..c4b0ef89 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 cd872b28..f3372074 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 6f8f5e19bd725bb17d439d233269974d89393029 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 10 Aug 2022 20:34:20 +0000 Subject: [PATCH 16/16] =?UTF-8?q?Bump=20version:=206.0.1=20=E2=86=92=206.1?= =?UTF-8?q?.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 de99fb6c..02119c94 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/ibm_watson/version.py b/ibm_watson/version.py index c4b0ef89..9f62d768 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 f3372074..766b8b23 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__))