From 6b87f9bc834f9b23e62a1d7047e8024839a50e36 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:18:28 -0400 Subject: [PATCH 1/7] feat(AssistantV2): add support for list logs and delete user data --- examples/assistant_v2.py | 5 + ibm_watson/assistant_v2.py | 588 +++++++++++++++++++++++++++++++++++-- 2 files changed, 568 insertions(+), 25 deletions(-) diff --git a/examples/assistant_v2.py b/examples/assistant_v2.py index bf81d13ab..90cd62728 100644 --- a/examples/assistant_v2.py +++ b/examples/assistant_v2.py @@ -31,3 +31,8 @@ } }).get_result() print(json.dumps(message, indent=2)) + +# logs = assistant.list_logs( +# "" +# ) +# print(json.dumps(logs, indent=2)) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index c0a3cb07e..9fa7594cf 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -39,7 +39,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'assistant' def __init__( @@ -186,7 +186,6 @@ def message(self, Send user input to an assistant and receive a response, with conversation state (including context data) stored by Watson Assistant for the duration of the session. - There is no rate limit for this operation. :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -251,7 +250,6 @@ def message_stateless(self, Send user input to an assistant and receive a response, with conversation state (including context data) managed by your application. - There is no rate limit for this operation. :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -303,6 +301,121 @@ def message_stateless(self, response = self.send(request) return response + ######################### + # Logs + ######################### + + def list_logs(self, + assistant_id: str, + *, + sort: str = None, + filter: str = None, + page_limit: int = None, + cursor: str = None, + **kwargs) -> 'DetailedResponse': + """ + List log events for an assistant. + + List the events from the log of an assistant. + This method is available only with Premium plans. + + :param str assistant_id: Unique identifier of the assistant. To find the + assistant ID in the Watson Assistant user interface, open the assistant + settings and click **API Details**. For information about creating + assistants, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :param str sort: (optional) How to sort the returned log events. You can + sort by **request_timestamp**. To reverse the sort order, prefix the + parameter value with a minus sign (`-`). + :param str filter: (optional) A cacheable parameter that limits the results + to those matching the specified filter. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-filter-reference#filter-reference). + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if assistant_id is None: + raise ValueError('assistant_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_logs') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'sort': sort, + 'filter': filter, + 'page_limit': page_limit, + 'cursor': cursor + } + + url = '/v2/assistants/{0}/logs'.format( + *self._encode_path_vars(assistant_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # User data + ######################### + + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + You associate a customer ID with data by passing the `X-Watson-Metadata` header + with a request that passes data. For more information about personal data and + customer IDs, see [Information + security](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security). + This operation is limited to 4 requests per minute. For more information, see + **Rate limiting**. + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if customer_id is None: + raise ValueError('customer_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data') + headers.update(sdk_headers) + + params = {'version': self.version, 'customer_id': customer_id} + + url = '/v2/user_data' + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ############################################################################## # Models @@ -812,9 +925,9 @@ class DialogSuggestion(): """ DialogSuggestion. - :attr str label: The user-facing label for the disambiguation option. This label - is taken from the **title** or **user_label** property of the corresponding - dialog node, depending on the disambiguation options. + :attr str label: The user-facing label for the suggestion. This label is taken + from the **title** or **user_label** property of the corresponding dialog node, + depending on the disambiguation options. :attr DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -830,9 +943,9 @@ def __init__(self, """ Initialize a DialogSuggestion object. - :param str label: The user-facing label for the disambiguation option. This - label is taken from the **title** or **user_label** property of the - corresponding dialog node, depending on the disambiguation options. + :param str label: The user-facing label for the suggestion. This label is + taken from the **title** or **user_label** property of the corresponding + dialog node, depending on the disambiguation options. :param DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -967,6 +1080,357 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other +class Log(): + """ + Log. + + :attr str log_id: A unique identifier for the logged event. + :attr MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :attr MessageResponse response: A response from the Watson Assistant service. + :attr str assistant_id: Unique identifier of the assistant. + :attr str session_id: The ID of the session the message was part of. + :attr str skill_id: The unique identifier of the skill that responded to the + message. + :attr str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :attr str request_timestamp: The timestamp for receipt of the message. + :attr str response_timestamp: The timestamp for the system response to the + message. + :attr str language: The language of the assistant to which the message request + was made. + :attr str customer_id: (optional) The customer ID specified for the message, if + any. + """ + + def __init__(self, + log_id: str, + request: 'MessageRequest', + response: 'MessageResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, + *, + customer_id: str = None) -> None: + """ + Initialize a Log object. + + :param str log_id: A unique identifier for the logged event. + :param MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :param MessageResponse response: A response from the Watson Assistant + service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to + the message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message + request was made. + :param str customer_id: (optional) The customer ID specified for the + message, if any. + """ + self.log_id = log_id + self.request = request + self.response = response + self.assistant_id = assistant_id + self.session_id = session_id + self.skill_id = skill_id + self.snapshot = snapshot + self.request_timestamp = request_timestamp + self.response_timestamp = response_timestamp + self.language = language + self.customer_id = customer_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Log': + """Initialize a Log object from a json dictionary.""" + args = {} + valid_keys = [ + 'log_id', 'request', 'response', 'assistant_id', 'session_id', + 'skill_id', 'snapshot', 'request_timestamp', 'response_timestamp', + 'language', 'customer_id' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Log: ' + + ', '.join(bad_keys)) + if 'log_id' in _dict: + args['log_id'] = _dict.get('log_id') + else: + raise ValueError( + 'Required property \'log_id\' not present in Log JSON') + if 'request' in _dict: + args['request'] = MessageRequest._from_dict(_dict.get('request')) + else: + raise ValueError( + 'Required property \'request\' not present in Log JSON') + if 'response' in _dict: + args['response'] = MessageResponse._from_dict(_dict.get('response')) + else: + raise ValueError( + 'Required property \'response\' not present in Log JSON') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + else: + raise ValueError( + 'Required property \'assistant_id\' not present in Log JSON') + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') + else: + raise ValueError( + 'Required property \'session_id\' not present in Log JSON') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in Log JSON') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + else: + raise ValueError( + 'Required property \'snapshot\' not present in Log JSON') + if 'request_timestamp' in _dict: + args['request_timestamp'] = _dict.get('request_timestamp') + else: + raise ValueError( + 'Required property \'request_timestamp\' not present in Log JSON' + ) + if 'response_timestamp' in _dict: + args['response_timestamp'] = _dict.get('response_timestamp') + else: + raise ValueError( + 'Required property \'response_timestamp\' not present in Log JSON' + ) + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in Log JSON') + if 'customer_id' in _dict: + args['customer_id'] = _dict.get('customer_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Log object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'log_id') and self.log_id is not None: + _dict['log_id'] = self.log_id + if hasattr(self, 'request') and self.request is not None: + _dict['request'] = self.request._to_dict() + if hasattr(self, 'response') and self.response is not None: + _dict['response'] = self.response._to_dict() + if hasattr(self, 'assistant_id') and self.assistant_id is not None: + _dict['assistant_id'] = self.assistant_id + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'request_timestamp') and self.request_timestamp is not None: + _dict['request_timestamp'] = self.request_timestamp + if hasattr( + self, + 'response_timestamp') and self.response_timestamp is not None: + _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'customer_id') and self.customer_id is not None: + _dict['customer_id'] = self.customer_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Log object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Log') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Log') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogCollection(): + """ + LogCollection. + + :attr List[Log] logs: An array of objects describing log events. + :attr LogPagination pagination: The pagination data for the returned objects. + """ + + def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + """ + Initialize a LogCollection object. + + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned + objects. + """ + self.logs = logs + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogCollection': + """Initialize a LogCollection object from a json dictionary.""" + args = {} + valid_keys = ['logs', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class LogCollection: ' + + ', '.join(bad_keys)) + if 'logs' in _dict: + args['logs'] = [Log._from_dict(x) for x in (_dict.get('logs'))] + else: + raise ValueError( + 'Required property \'logs\' not present in LogCollection JSON') + if 'pagination' in _dict: + args['pagination'] = LogPagination._from_dict( + _dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in LogCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'logs') and self.logs is not None: + _dict['logs'] = [x._to_dict() for x in self.logs] + if hasattr(self, 'pagination') and self.pagination is not None: + _dict['pagination'] = self.pagination._to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogCollection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'LogCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogPagination(): + """ + The pagination data for the returned objects. + + :attr str next_url: (optional) The URL that will return the next page of + results, if any. + :attr int matched: (optional) Reserved for future use. + :attr str next_cursor: (optional) A token identifying the next page of results. + """ + + def __init__(self, + *, + next_url: str = None, + matched: int = None, + next_cursor: str = None) -> None: + """ + Initialize a LogPagination object. + + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of + results. + """ + self.next_url = next_url + self.matched = matched + self.next_cursor = next_cursor + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogPagination': + """Initialize a LogPagination object from a json dictionary.""" + args = {} + valid_keys = ['next_url', 'matched', 'next_cursor'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class LogPagination: ' + + ', '.join(bad_keys)) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogPagination object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogPagination object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'LogPagination') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogPagination') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageContext(): """ MessageContext. @@ -2611,6 +3075,88 @@ def __ne__(self, other: 'MessageOutputSpelling') -> bool: return not self == other +class MessageRequest(): + """ + A stateful message request formatted for the Watson Assistant service. + + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + """ + + def __init__(self, + *, + input: 'MessageInput' = None, + context: 'MessageContext' = None) -> None: + """ + Initialize a MessageRequest object. + + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + """ + self.input = input + self.context = context + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageRequest': + """Initialize a MessageRequest object from a json dictionary.""" + args = {} + valid_keys = ['input', 'context'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageRequest: ' + + ', '.join(bad_keys)) + if 'input' in _dict: + args['input'] = MessageInput._from_dict(_dict.get('input')) + if 'context' in _dict: + args['context'] = MessageContext._from_dict(_dict.get('context')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageRequest object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input') and self.input is not None: + _dict['input'] = self.input._to_dict() + if hasattr(self, 'context') and self.context is not None: + _dict['context'] = self.context._to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageRequest object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageRequest') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageRequest') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageResponse(): """ A response from the Watson Assistant service. @@ -2621,7 +3167,8 @@ class MessageResponse(): can use this property to access context variables. The context is stored by the assistant on a per-session basis. **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. + **return_context**=`true` in the message request. Full context is always + included in logs. """ def __init__(self, @@ -2637,7 +3184,8 @@ def __init__(self, conversation. You can use this property to access context variables. The context is stored by the assistant on a per-session basis. **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. + **return_context**=`true` in the message request. Full context is always + included in logs. """ self.output = output self.context = context @@ -3573,8 +4121,6 @@ class RuntimeResponseGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Premium users. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during @@ -3592,8 +4138,6 @@ class RuntimeResponseGeneric(): derived from the **user_label** property of the relevant node. :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, - which is only available for Premium users. :attr str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. :attr List[SearchResult] results: (optional) An array of objects containing @@ -3622,8 +4166,6 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Premium users. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event @@ -3644,8 +4186,6 @@ def __init__(self, :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation - feature, which is only available for Premium users. :param str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. :param List[SearchResult] results: (optional) An array of objects @@ -3783,8 +4323,6 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Premium users. """ TEXT = "text" PAUSE = "pause" @@ -3808,8 +4346,8 @@ class SearchResult(): :attr str id: The unique identifier of the document in the Discovery service collection. - This property is included in responses from search skills, which are a beta - feature available only to Plus or Premium plan users. + This property is included in responses from search skills, which are available + only to Plus or Premium plan users. :attr SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. :attr str body: (optional) A description of the search result. This is taken @@ -3838,8 +4376,8 @@ def __init__(self, :param str id: The unique identifier of the document in the Discovery service collection. - This property is included in responses from search skills, which are a beta - feature available only to Plus or Premium plan users. + This property is included in responses from search skills, which are + available only to Plus or Premium plan users. :param SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. :param str body: (optional) A description of the search result. This is From de83e96e5d4b0a9f2221fc48ca38ef66b0a0c68d Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:19:37 -0400 Subject: [PATCH 2/7] feat(languageTranslatorV3): add support for list languages --- ibm_watson/language_translator_v3.py | 429 +++++++++++++++--- .../test_language_translator_v3.py | 4 + 2 files changed, 380 insertions(+), 53 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 7e98d4908..072f7a1de 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -15,7 +15,7 @@ # limitations under the License. """ IBM Watson™ Language Translator translates text from one language to another. The -service offers multiple IBM provided translation models that you can customize based on +service offers multiple IBM-provided translation models that you can customize based on your unique terminology and language. Use Language Translator to take news from across the globe and present it in your language, communicate with your customers in their own language, and more. @@ -43,7 +43,7 @@ class LanguageTranslatorV3(BaseService): """The Language Translator V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/language-translator/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.language-translator.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'language_translator' def __init__( @@ -79,6 +79,42 @@ def __init__( self.version = version self.configure_service(service_name) + ######################### + # Languages + ######################### + + def list_languages(self, **kwargs) -> 'DetailedResponse': + """ + List supported languages. + + Lists all supported languages. The method returns an array of supported languages + with information about each language. Languages are listed in alphabetical order + by language code (for example, `af`, `ar`). + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_languages') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v3/languages' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ######################### # Translation ######################### @@ -93,19 +129,24 @@ def translate(self, """ Translate. - Translates the input text from the source language to the target language. A - target language or translation model ID is required. The service attempts to - detect the language of the source text if it is not specified. + Translates the input text from the source language to the target language. Specify + a model ID that indicates the source and target languages, or specify the source + and target languages individually. You can omit the source language to have the + service attempt to detect the language from the input text. If you omit the source + language, the request must contain sufficient input text for the service to + identify the source language. - :param List[str] text: Input text in UTF-8 encoding. Multiple entries will + :param List[str] text: Input text in UTF-8 encoding. Multiple entries result in multiple translations in the response. :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM provided base model for English to German - translation. A model ID overrides the source and target parameters and is - required if you use a custom model. If no model ID is specified, you must - specify a target language. + example, `en-de` selects the IBM-provided base model for English-to-German + translation. A model ID overrides the `source` and `target` parameters and + is required if you use a custom model. If no model ID is specified, you + must specify at least a target language. :param str source: (optional) Language code that specifies the language of - the source document. + the input text. If omitted, the service derives the source language from + the input text. The input must contain sufficient text for the service to + identify the language reliably. :param str target: (optional) Language code that specifies the target language for translation. Required if model ID is not specified. :param dict headers: A `dict` containing the request headers @@ -236,11 +277,11 @@ def list_models(self, source language. :param str target: (optional) Specify a language code to filter results by target language. - :param bool default: (optional) If the default parameter isn't specified, - the service will return all models (default and non-default) for each - language pair. To return only default models, set this to `true`. To return - only non-default models, set this to `false`. There is exactly one default - model per language pair, the IBM provided base model. + :param bool default: (optional) If the `default` parameter isn't specified, + the service returns all models (default and non-default) for each language + pair. To return only default models, set this parameter to `true`. To + return only non-default models, set this parameter to `false`. There is + exactly one default model, the IBM-provided base model, per language pair. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -280,39 +321,90 @@ def create_model(self, """ Create model. - Uploads Translation Memory eXchange (TMX) files to customize a translation model. - You can either customize a model with a forced glossary or with a corpus that - contains parallel sentences. To create a model that is customized with a parallel - corpus and a forced glossary, proceed in two steps: customize with a - parallel corpus first and then customize the resulting model with a glossary. - Depending on the type of customization and the size of the uploaded corpora, - training can range from minutes for a glossary to several hours for a large - parallel corpus. You can upload a single forced glossary file and this file must - be less than 10 MB. You can upload multiple parallel corpora tmx files. The - cumulative file size of all uploaded files is limited to 250 MB. To - successfully train with a parallel corpus you must have at least 5,000 parallel - sentences in your corpus. - You can have a maximum of 10 custom models per language pair. - - :param str base_model_id: The model ID of the model to use as the base for - customization. To see available models, use the `List models` method. - Usually all IBM provided models are customizable. In addition, all your - models that have been created via parallel corpus customization, can be - further customized with a forced glossary. - :param TextIO forced_glossary: (optional) A TMX file with your - customizations. The customizations in the file completely overwrite the - domain translaton data, including high frequency or high confidence phrase - translations. You can upload only one glossary with a file size less than - 10 MB per call. A forced glossary should contain single words or short - phrases. - :param TextIO parallel_corpus: (optional) A TMX file with parallel - sentences for source and target language. You can upload multiple - parallel_corpus files in one request. All uploaded parallel_corpus files - combined, your parallel corpus must contain at least 5,000 parallel - sentences to train successfully. + Uploads training files to customize a translation model. You can customize a model + with a forced glossary or with a parallel corpus: + * Use a *forced glossary* to force certain terms and phrases to be translated in a + specific way. You can upload only a single forced glossary file for a model. The + size of a forced glossary file for a custom model is limited to 10 MB. + * Use a *parallel corpus* when you want your custom model to learn from general + translation patterns in parallel sentences in your samples. What your model learns + from a parallel corpus can improve translation results for input text that the + model has not been trained on. You can upload multiple parallel corpora files with + a request. To successfully train with parallel corpora, the corpora files must + contain a cumulative total of at least 5000 parallel sentences. The cumulative + size of all uploaded corpus files for a custom model is limited to 250 MB. + Depending on the type of customization and the size of the uploaded files, + training time can range from minutes for a glossary to several hours for a large + parallel corpus. To create a model that is customized with a parallel corpus and a + forced glossary, customize the model with a parallel corpus first and then + customize the resulting model with a forced glossary. + You can create a maximum of 10 custom models per language pair. For more + information about customizing a translation model, including the formatting and + character restrictions for data files, see [Customizing your + model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing). + #### Supported file formats + You can provide your training data for customization in the following document + formats: + * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for + the exchange of translation memories. + * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an + XML specification for the exchange of translation memories. + * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for + aligned sentences and phrases. The first row contains the language code. + * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns + for aligned sentences and phrases. The first row contains the language code. + * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and + phrases. + * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns + for aligned sentences and phrases. The first row contains the language code. + You must encode all text data in UTF-8 format. For more information, see + [Supported document formats for training + data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data). + #### Specifying file formats + You can indicate the format of a file by including the file extension with the + file name. Use the file extensions shown in **Supported file formats**. + Alternatively, you can omit the file extension and specify one of the following + `content-type` specifications for the file: + * **TMX** - `application/x-tmx+xml` + * **XLIFF** - `application/xliff+xml` + * **CSV** - `text/csv` + * **TSV** - `text/tab-separated-values` + * **JSON** - `application/json` + * **Microsoft Excel** - + `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` + For example, with `curl`, use the following `content-type` specification to + indicate the format of a CSV file named **glossary**: + `--form "forced_glossary=@glossary;type=text/csv"`. + + :param str base_model_id: The ID of the translation model to use as the + base for customization. To see available models and IDs, use the `List + models` method. Most models that are provided with the service are + customizable. In addition, all models that you create with parallel corpora + customization can be further customized with a forced glossary. + :param TextIO forced_glossary: (optional) A file with forced glossary terms + for the source and target languages. The customizations in the file + completely overwrite the domain translation data, including high frequency + or high confidence phrase translations. + You can upload only one glossary file for a custom model, and the glossary + can have a maximum size of 10 MB. A forced glossary must contain single + words or short phrases. For more information, see **Supported file + formats** in the method description. + *With `curl`, use `--form forced_glossary=@{filename}`.*. + :param TextIO parallel_corpus: (optional) A file with parallel sentences + for the source and target languages. You can upload multiple parallel + corpus files in one request by repeating the parameter. All uploaded + parallel corpus files combined must contain at least 5000 parallel + sentences to train successfully. You can provide a maximum of 500,000 + parallel sentences across all corpora. + A single entry in a corpus file can contain a maximum of 80 words. All + corpora files for a custom model can have a cumulative maximum size of 250 + MB. For more information, see **Supported file formats** in the method + description. + *With `curl`, use `--form parallel_corpus=@{filename}`.*. :param str name: (optional) An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, - underscores, spaces and apostrophes. The maximum length is 32 characters. + underscores, spaces, and apostrophes. The maximum length of the name is 32 + characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -393,7 +485,7 @@ def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': Gets information about a translation model, including training status for custom models. Use this API call to poll the status of your customization request. A - successfully completed training will have a status of `available`. + successfully completed training has a status of `available`. :param str model_id: Model ID of the model to get. :param dict headers: A `dict` containing the request headers @@ -481,12 +573,14 @@ def translate_document(self, :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM provided base model for English to German - translation. A model ID overrides the source and target parameters and is - required if you use a custom model. If no model ID is specified, you must - specify a target language. + example, `en-de` selects the IBM-provided base model for English-to-German + translation. A model ID overrides the `source` and `target` parameters and + is required if you use a custom model. If no model ID is specified, you + must specify at least a target language. :param str source: (optional) Language code that specifies the language of - the source document. + the source document. If omitted, the service derives the source language + from the input text. The input must contain sufficient text for the service + to identify the language reliably. :param str target: (optional) Language code that specifies the target language for translation. Required if model ID is not specified. :param str document_id: (optional) To use a previously submitted document @@ -1378,6 +1472,235 @@ def __ne__(self, other: 'IdentifiedLanguages') -> bool: return not self == other +class Language(): + """ + Response payload for languages. + + :attr str language: (optional) The language code for the language (for example, + `af`). + :attr str language_name: (optional) The name of the language in English (for + example, `Afrikaans`). + :attr str native_language_name: (optional) The native name of the language (for + example, `Afrikaans`). + :attr str country_code: (optional) The country code for the language (for + example, `ZA` for South Africa). + :attr bool words_separated: (optional) Indicates whether words of the language + are separated by whitespace: `true` if the words are separated; `false` + otherwise. + :attr str direction: (optional) Indicates the direction of the language: + `right_to_left` or `left_to_right`. + :attr bool supported_as_source: (optional) Indicates whether the language can be + used as the source for translation: `true` if the language can be used as the + source; `false` otherwise. + :attr bool supported_as_target: (optional) Indicates whether the language can be + used as the target for translation: `true` if the language can be used as the + target; `false` otherwise. + :attr bool identifiable: (optional) Indicates whether the language supports + automatic detection: `true` if the language can be detected automatically; + `false` otherwise. + """ + + def __init__(self, + *, + language: str = None, + language_name: str = None, + native_language_name: str = None, + country_code: str = None, + words_separated: bool = None, + direction: str = None, + supported_as_source: bool = None, + supported_as_target: bool = None, + identifiable: bool = None) -> None: + """ + Initialize a Language object. + + :param str language: (optional) The language code for the language (for + example, `af`). + :param str language_name: (optional) The name of the language in English + (for example, `Afrikaans`). + :param str native_language_name: (optional) The native name of the language + (for example, `Afrikaans`). + :param str country_code: (optional) The country code for the language (for + example, `ZA` for South Africa). + :param bool words_separated: (optional) Indicates whether words of the + language are separated by whitespace: `true` if the words are separated; + `false` otherwise. + :param str direction: (optional) Indicates the direction of the language: + `right_to_left` or `left_to_right`. + :param bool supported_as_source: (optional) Indicates whether the language + can be used as the source for translation: `true` if the language can be + used as the source; `false` otherwise. + :param bool supported_as_target: (optional) Indicates whether the language + can be used as the target for translation: `true` if the language can be + used as the target; `false` otherwise. + :param bool identifiable: (optional) Indicates whether the language + supports automatic detection: `true` if the language can be detected + automatically; `false` otherwise. + """ + self.language = language + self.language_name = language_name + self.native_language_name = native_language_name + self.country_code = country_code + self.words_separated = words_separated + self.direction = direction + self.supported_as_source = supported_as_source + self.supported_as_target = supported_as_target + self.identifiable = identifiable + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Language': + """Initialize a Language object from a json dictionary.""" + args = {} + valid_keys = [ + 'language', 'language_name', 'native_language_name', 'country_code', + 'words_separated', 'direction', 'supported_as_source', + 'supported_as_target', 'identifiable' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Language: ' + + ', '.join(bad_keys)) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'language_name' in _dict: + args['language_name'] = _dict.get('language_name') + if 'native_language_name' in _dict: + args['native_language_name'] = _dict.get('native_language_name') + if 'country_code' in _dict: + args['country_code'] = _dict.get('country_code') + if 'words_separated' in _dict: + args['words_separated'] = _dict.get('words_separated') + if 'direction' in _dict: + args['direction'] = _dict.get('direction') + if 'supported_as_source' in _dict: + args['supported_as_source'] = _dict.get('supported_as_source') + if 'supported_as_target' in _dict: + args['supported_as_target'] = _dict.get('supported_as_target') + if 'identifiable' in _dict: + args['identifiable'] = _dict.get('identifiable') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Language object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'language_name') and self.language_name is not None: + _dict['language_name'] = self.language_name + if hasattr(self, 'native_language_name' + ) and self.native_language_name is not None: + _dict['native_language_name'] = self.native_language_name + if hasattr(self, 'country_code') and self.country_code is not None: + _dict['country_code'] = self.country_code + if hasattr(self, + 'words_separated') and self.words_separated is not None: + _dict['words_separated'] = self.words_separated + if hasattr(self, 'direction') and self.direction is not None: + _dict['direction'] = self.direction + if hasattr( + self, + 'supported_as_source') and self.supported_as_source is not None: + _dict['supported_as_source'] = self.supported_as_source + if hasattr( + self, + 'supported_as_target') and self.supported_as_target is not None: + _dict['supported_as_target'] = self.supported_as_target + if hasattr(self, 'identifiable') and self.identifiable is not None: + _dict['identifiable'] = self.identifiable + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Language object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Language') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Language') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Languages(): + """ + The response type for listing supported languages. + + :attr List[Language] languages: An array of supported languages with information + about each language. + """ + + def __init__(self, languages: List['Language']) -> None: + """ + Initialize a Languages object. + + :param List[Language] languages: An array of supported languages with + information about each language. + """ + self.languages = languages + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Languages': + """Initialize a Languages object from a json dictionary.""" + args = {} + valid_keys = ['languages'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Languages: ' + + ', '.join(bad_keys)) + if 'languages' in _dict: + args['languages'] = [ + Language._from_dict(x) for x in (_dict.get('languages')) + ] + else: + raise ValueError( + 'Required property \'languages\' not present in Languages JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Languages object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'languages') and self.languages is not None: + _dict['languages'] = [x._to_dict() for x in self.languages] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Languages object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Languages') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Languages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Translation(): """ Translation. diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py index b44ece2a7..439a5322f 100644 --- a/test/integration/test_language_translator_v3.py +++ b/test/integration/test_language_translator_v3.py @@ -23,6 +23,10 @@ def test_translate(self): text='Hello, how are you?', target='es').get_result() assert translation is not None + def test_list_languages(self): + languages = self.language_translator.list_languages() + assert languages is not None + def test_document_translation(self): with open(join(dirname(__file__), '../../resources/hello_world.txt'), 'r') as fileinfo: From 4388ea276b5473b13249592127a51e2004a1d82c Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:23:09 -0400 Subject: [PATCH 3/7] feat(discoV2): add new apis for enrichments, collections and projects --- ibm_watson/discovery_v2.py | 3757 ++++++++++++++++++++----- test/integration/test_discovery_v2.py | 110 + 2 files changed, 3193 insertions(+), 674 deletions(-) create mode 100644 test/integration/test_discovery_v2.py diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index f4341d9cb..947486b88 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -IBM Watson™ Discovery for IBM Cloud Pak for Data is a cognitive search and content -analytics engine that you can add to applications to identify patterns, trends and -actionable insights to drive better decision-making. Securely unify structured and -unstructured data with pre-enriched content, and use a simplified query language to -eliminate the need for manual filtering of results. +IBM Watson™ Discovery is a cognitive search and content analytics engine that you +can add to applications to identify patterns, trends and actionable insights to drive +better decision-making. Securely unify structured and unstructured data with pre-enriched +content, and use a simplified query language to eliminate the need for manual filtering of +results. """ import json @@ -44,7 +44,7 @@ class DiscoveryV2(BaseService): """The Discovery V2 service.""" - DEFAULT_SERVICE_URL = None + DEFAULT_SERVICE_URL = 'https://api.us-south.discovery.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'discovery' def __init__( @@ -120,6 +120,206 @@ def list_collections(self, project_id: str, **kwargs) -> 'DetailedResponse': response = self.send(request) return response + def create_collection(self, + project_id: str, + name: str, + *, + description: str = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None, + **kwargs) -> 'DetailedResponse': + """ + Create a collection. + + Create a new collection in the specified project. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if name is None: + raise ValueError('name must be provided') + if enrichments is not None: + enrichments = [self._convert_model(x) for x in enrichments] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'language': language, + 'enrichments': enrichments + } + + url = '/v2/projects/{0}/collections'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def get_collection(self, project_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': + """ + Get collection. + + Get details about the specified collection. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/collections/{1}'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_collection(self, + project_id: str, + collection_id: str, + *, + name: str = None, + description: str = None, + enrichments: List['CollectionEnrichment'] = None, + **kwargs) -> 'DetailedResponse': + """ + Update a collection. + + Updates the specified collection's name, description, and enrichments. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param str name: (optional) The name of the collection. + :param str description: (optional) A description of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + if enrichments is not None: + enrichments = [self._convert_model(x) for x in enrichments] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'enrichments': enrichments + } + + url = '/v2/projects/{0}/collections/{1}'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def delete_collection(self, project_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete a collection. + + Deletes the specified collection from the project. All documents stored in the + specified collection and not shared is also deleted. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/collections/{1}'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ######################### # Queries ######################### @@ -147,6 +347,12 @@ def query(self, By using this method, you can construct queries. For details, see the [Discovery documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). + The default query parameters are defined by the settings for this project, see the + [Discovery + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-project-defaults) + for an overview of the standard default settings, and see [the Projects API + documentation](#create-project) for details about how to set custom default query + settings. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. @@ -427,7 +633,7 @@ def list_fields(self, def get_component_settings(self, project_id: str, **kwargs) -> 'DetailedResponse': """ - Configuration settings for components. + List component settings. Returns default configuration settings for components. @@ -512,7 +718,8 @@ def add_document(self, :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + 1 MB. Metadata parts larger than 1 MB are rejected. + Example: ``` { "Creator": "Johnny Appleseed", "Subject": "Apples" } ```. @@ -599,7 +806,8 @@ def update_document(self, :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + 1 MB. Metadata parts larger than 1 MB are rejected. + Example: ``` { "Creator": "Johnny Appleseed", "Subject": "Apples" } ```. @@ -951,149 +1159,1768 @@ def update_training_query(self, response = self.send(request) return response + ######################### + # enrichments + ######################### -class AddDocumentEnums(object): - - class FileContentType(Enum): + def list_enrichments(self, project_id: str, **kwargs) -> 'DetailedResponse': """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + List Enrichments. + List the enrichments available to this project. -class UpdateDocumentEnums(object): - - class FileContentType(Enum): - """ - The content type of file. + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + if project_id is None: + raise ValueError('project_id must be provided') -############################################################################## -# Models -############################################################################## + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_enrichments') + headers.update(sdk_headers) + params = {'version': self.version} -class Collection(): - """ - A collection for storing documents. + url = '/v2/projects/{0}/enrichments'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. - """ + response = self.send(request) + return response - def __init__(self, *, collection_id: str = None, name: str = None) -> None: + def create_enrichment(self, + project_id: str, + enrichment: 'CreateEnrichment', + *, + file: BinaryIO = None, + **kwargs) -> 'DetailedResponse': """ - Initialize a Collection object. + Create an enrichment. - :param str collection_id: (optional) The unique identifier of the - collection. - :param str name: (optional) The name of the collection. - """ - self.collection_id = collection_id - self.name = name + Create an enrichment for use with the specified project/. - @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" - args = {} - valid_keys = ['collection_id', 'name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Collection: ' - + ', '.join(bad_keys)) - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - return cls(**args) + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param CreateEnrichment enrichment: + :param TextIO file: (optional) The enrichment file to upload. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ - @classmethod - def _from_dict(cls, _dict): - """Initialize a Collection object from a json dictionary.""" - return cls.from_dict(_dict) + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment is None: + raise ValueError('enrichment must be provided') - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - return _dict + print(enrichment) + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_enrichment') + headers.update(sdk_headers) - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + params = {'version': self.version} - def __str__(self) -> str: - """Return a `str` version of this Collection object.""" - return json.dumps(self._to_dict(), indent=2) + form_data = [] + form_data.append(('enrichment', (None, json.dumps(enrichment), 'application/json'))) + if file: + form_data.append(('file', (None, file, 'application/octet-stream'))) - def __eq__(self, other: 'Collection') -> bool: + url = '/v2/projects/{0}/enrichments'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def get_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> 'DetailedResponse': + """ + Get enrichment. + + Get details about a specific enrichment. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_enrichment') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/enrichments/{1}'.format( + *self._encode_path_vars(project_id, enrichment_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_enrichment(self, + project_id: str, + enrichment_id: str, + name: str, + *, + description: str = None, + **kwargs) -> 'DetailedResponse': + """ + Update an enrichment. + + Updates an existing enrichment's name and description. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str enrichment_id: The ID of the enrichment. + :param str name: A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_id must be provided') + if name is None: + raise ValueError('name must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_enrichment') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'name': name, 'description': description} + + url = '/v2/projects/{0}/enrichments/{1}'.format( + *self._encode_path_vars(project_id, enrichment_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def delete_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete an enrichment. + + Deletes an existing enrichment from the specified project. + **Note:** Only enrichments that have been manually created can be deleted. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_enrichment') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/enrichments/{1}'.format( + *self._encode_path_vars(project_id, enrichment_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # projects + ######################### + + def list_projects(self, **kwargs) -> 'DetailedResponse': + """ + List projects. + + Lists existing projects for this instance. + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_projects') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def create_project(self, + name: str, + type: str, + *, + default_query_parameters: 'DefaultQueryParams' = None, + **kwargs) -> 'DetailedResponse': + """ + Create a Project. + + Create a new project for this instance. + + :param str name: The human readable name of this project. + :param str type: The project type of this project. + :param DefaultQueryParams default_query_parameters: (optional) Default + query parameters for this project. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if name is None: + raise ValueError('name must be provided') + if type is None: + raise ValueError('type must be provided') + if default_query_parameters is not None: + default_query_parameters = self._convert_model( + default_query_parameters) + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'type': type, + 'default_query_parameters': default_query_parameters + } + + url = '/v2/projects' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def get_project(self, project_id: str, **kwargs) -> 'DetailedResponse': + """ + Get project. + + Get details on the specified project. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_project(self, + project_id: str, + *, + name: str = None, + **kwargs) -> 'DetailedResponse': + """ + Update a project. + + Update the specified project's name. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str name: (optional) The new name to give this project. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'name': name} + + url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def delete_project(self, project_id: str, **kwargs) -> 'DetailedResponse': + """ + Delete a project. + + Deletes the specified project. + **Important:** Deleting a project deletes everything that is part of the specified + project, including all collections. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # userData + ######################### + + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + You associate a customer ID with data by passing the **X-Watson-Metadata** header + with a request that passes data. For more information about personal data and + customer IDs, see [Information + security](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-information-security#information-security). + **Note:** This method is only supported on IBM Cloud instances of Discovery. + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if customer_id is None: + raise ValueError('customer_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data') + headers.update(sdk_headers) + + params = {'version': self.version, 'customer_id': customer_id} + + url = '/v2/user_data' + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + +class AddDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class UpdateDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +############################################################################## +# Models +############################################################################## + + +class Collection(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: (optional) The name of the collection. + """ + + def __init__(self, *, collection_id: str = None, name: str = None) -> None: + """ + Initialize a Collection object. + + :param str collection_id: (optional) The unique identifier of the + collection. + :param str name: (optional) The name of the collection. + """ + self.collection_id = collection_id + self.name = name + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Collection': + """Initialize a Collection object from a json dictionary.""" + args = {} + valid_keys = ['collection_id', 'name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Collection: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Collection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Collection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Collection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetails(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: The name of the collection. + :attr str description: (optional) A description of the collection. + :attr datetime created: (optional) The date that the collection was created. + :attr str language: (optional) The language of the collection. + :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments + that are applied to this collection. + """ + + def __init__(self, + name: str, + *, + collection_id: str = None, + description: str = None, + created: datetime = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None) -> None: + """ + Initialize a CollectionDetails object. + + :param str name: The name of the collection. + :param str collection_id: (optional) The unique identifier of the + collection. + :param str description: (optional) A description of the collection. + :param datetime created: (optional) The date that the collection was + created. + :param str language: (optional) The language of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. + """ + self.collection_id = collection_id + self.name = name + self.description = description + self.created = created + self.language = language + self.enrichments = enrichments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionDetails': + """Initialize a CollectionDetails object from a json dictionary.""" + args = {} + valid_keys = [ + 'collection_id', 'name', 'description', 'created', 'language', + 'enrichments' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CollectionDetails: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in CollectionDetails JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'enrichments' in _dict: + args['enrichments'] = [ + CollectionEnrichment._from_dict(x) + for x in (_dict.get('enrichments')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetails object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'enrichments') and self.enrichments is not None: + _dict['enrichments'] = [x._to_dict() for x in self.enrichments] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionDetails object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CollectionDetails') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CollectionDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionEnrichment(): + """ + An object describing an Enrichment for a collection. + + :attr str enrichment_id: (optional) The unique identifier of this enrichment. + :attr List[str] fields: (optional) An array of field names that the enrichment + is applied to. + """ + + def __init__(self, + *, + enrichment_id: str = None, + fields: List[str] = None) -> None: + """ + Initialize a CollectionEnrichment object. + + :param str enrichment_id: (optional) The unique identifier of this + enrichment. + :param List[str] fields: (optional) An array of field names that the + enrichment is applied to. + """ + self.enrichment_id = enrichment_id + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': + """Initialize a CollectionEnrichment object from a json dictionary.""" + args = {} + valid_keys = ['enrichment_id', 'fields'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CollectionEnrichment: ' + + ', '.join(bad_keys)) + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionEnrichment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionEnrichment object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Completions(): + """ + An object containing an array of autocompletion suggestions. + + :attr List[str] completions: (optional) Array of autcomplete suggestion based on + the provided prefix. + """ + + def __init__(self, *, completions: List[str] = None) -> None: + """ + Initialize a Completions object. + + :param List[str] completions: (optional) Array of autcomplete suggestion + based on the provided prefix. + """ + self.completions = completions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Completions': + """Initialize a Completions object from a json dictionary.""" + args = {} + valid_keys = ['completions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Completions: ' + + ', '.join(bad_keys)) + if 'completions' in _dict: + args['completions'] = _dict.get('completions') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'completions') and self.completions is not None: + _dict['completions'] = self.completions + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Completions object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Completions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Completions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsAggregation(): + """ + Display settings for aggregations. + + :attr str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :attr str label: (optional) User-friendly alias for the aggregation. + :attr bool multiple_selections_allowed: (optional) Whether users is allowed to + select more than one of the aggregation terms. + :attr str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + + def __init__(self, + *, + name: str = None, + label: str = None, + multiple_selections_allowed: bool = None, + visualization_type: str = None) -> None: + """ + Initialize a ComponentSettingsAggregation object. + + :param str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is + allowed to select more than one of the aggregation terms. + :param str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + self.name = name + self.label = label + self.multiple_selections_allowed = multiple_selections_allowed + self.visualization_type = visualization_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + args = {} + valid_keys = [ + 'name', 'label', 'multiple_selections_allowed', 'visualization_type' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsAggregation: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'label' in _dict: + args['label'] = _dict.get('label') + if 'multiple_selections_allowed' in _dict: + args['multiple_selections_allowed'] = _dict.get( + 'multiple_selections_allowed') + if 'visualization_type' in _dict: + args['visualization_type'] = _dict.get('visualization_type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'multiple_selections_allowed' + ) and self.multiple_selections_allowed is not None: + _dict[ + 'multiple_selections_allowed'] = self.multiple_selections_allowed + if hasattr( + self, + 'visualization_type') and self.visualization_type is not None: + _dict['visualization_type'] = self.visualization_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class VisualizationTypeEnum(Enum): + """ + Type of visualization to use when rendering the aggregation. + """ + AUTO = "auto" + FACET_TABLE = "facet_table" + WORD_CLOUD = "word_cloud" + MAP = "map" + + +class ComponentSettingsFieldsShown(): + """ + Fields shown in the results section of the UI. + + :attr ComponentSettingsFieldsShownBody body: (optional) Body label. + :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + + def __init__(self, + *, + body: 'ComponentSettingsFieldsShownBody' = None, + title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + """ + Initialize a ComponentSettingsFieldsShown object. + + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + args = {} + valid_keys = ['body', 'title'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShown: ' + + ', '.join(bad_keys)) + if 'body' in _dict: + args['body'] = ComponentSettingsFieldsShownBody._from_dict( + _dict.get('body')) + if 'title' in _dict: + args['title'] = ComponentSettingsFieldsShownTitle._from_dict( + _dict.get('title')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body._to_dict() + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title._to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsFieldsShown object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownBody(): + """ + Body label. + + :attr bool use_passage: (optional) Use the whole passage as the body. + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + """ + Initialize a ComponentSettingsFieldsShownBody object. + + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. + """ + self.use_passage = use_passage + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + args = {} + valid_keys = ['use_passage', 'field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownBody: ' + + ', '.join(bad_keys)) + if 'use_passage' in _dict: + args['use_passage'] = _dict.get('use_passage') + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'use_passage') and self.use_passage is not None: + _dict['use_passage'] = self.use_passage + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownTitle(): + """ + Title label. + + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, field: str = None) -> None: + """ + Initialize a ComponentSettingsFieldsShownTitle object. + + :param str field: (optional) Use a specific field as the title. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + args = {} + valid_keys = ['field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownTitle: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsResponse(): + """ + The default component settings for this project. + + :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + results section of the UI. + :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. + :attr bool structured_search: (optional) Whether or not structured search is + enabled. + :attr int results_per_page: (optional) Number or results shown per page. + :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of + component setting aggregations. + """ + + def __init__( + self, + *, + fields_shown: 'ComponentSettingsFieldsShown' = None, + autocomplete: bool = None, + structured_search: bool = None, + results_per_page: int = None, + aggregations: List['ComponentSettingsAggregation'] = None) -> None: + """ + Initialize a ComponentSettingsResponse object. + + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown + in the results section of the UI. + :param bool autocomplete: (optional) Whether or not autocomplete is + enabled. + :param bool structured_search: (optional) Whether or not structured search + is enabled. + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list + of component setting aggregations. + """ + self.fields_shown = fields_shown + self.autocomplete = autocomplete + self.structured_search = structured_search + self.results_per_page = results_per_page + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': + """Initialize a ComponentSettingsResponse object from a json dictionary.""" + args = {} + valid_keys = [ + 'fields_shown', 'autocomplete', 'structured_search', + 'results_per_page', 'aggregations' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsResponse: ' + + ', '.join(bad_keys)) + if 'fields_shown' in _dict: + args['fields_shown'] = ComponentSettingsFieldsShown._from_dict( + _dict.get('fields_shown')) + if 'autocomplete' in _dict: + args['autocomplete'] = _dict.get('autocomplete') + if 'structured_search' in _dict: + args['structured_search'] = _dict.get('structured_search') + if 'results_per_page' in _dict: + args['results_per_page'] = _dict.get('results_per_page') + if 'aggregations' in _dict: + args['aggregations'] = [ + ComponentSettingsAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'fields_shown') and self.fields_shown is not None: + _dict['fields_shown'] = self.fields_shown._to_dict() + if hasattr(self, 'autocomplete') and self.autocomplete is not None: + _dict['autocomplete'] = self.autocomplete + if hasattr(self, + 'structured_search') and self.structured_search is not None: + _dict['structured_search'] = self.structured_search + if hasattr(self, + 'results_per_page') and self.results_per_page is not None: + _dict['results_per_page'] = self.results_per_page + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CreateEnrichment(): + """ + Information about a specific enrichment. + + :attr str name: (optional) The human readable name for this enrichment. + :attr str description: (optional) The description of this enrichment. + :attr str type: (optional) The type of this enrichment. + :attr EnrichmentOptions options: (optional) A object containing options for the + current enrichment. + """ + + def __init__(self, + *, + name: str = None, + description: str = None, + type: str = None, + options: 'EnrichmentOptions' = None) -> None: + """ + Initialize a CreateEnrichment object. + + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. + :param EnrichmentOptions options: (optional) A object containing options + for the current enrichment. + """ + self.name = name + self.description = description + self.type = type + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': + """Initialize a CreateEnrichment object from a json dictionary.""" + args = {} + valid_keys = ['name', 'description', 'type', 'options'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CreateEnrichment: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'options' in _dict: + args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateEnrichment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options._to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CreateEnrichment object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CreateEnrichment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateEnrichment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + The type of this enrichment. + """ + DICTIONARY = "dictionary" + REGULAR_EXPRESSION = "regular_expression" + UIMA_ANNOTATOR = "uima_annotator" + RULE_BASED = "rule_based" + WATSON_KNOWLEDGE_STUDIO_MODEL = "watson_knowledge_studio_model" + + +class DefaultQueryParams(): + """ + Default query parameters for this project. + + :attr List[str] collection_ids: (optional) An array of collection identifiers to + query. If empty or omitted all collections in the project are queried. + :attr DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :attr DefaultQueryParamsTableResults table_results: (optional) Default project + query settings for table results. + :attr str aggregation: (optional) A string representing the default aggregation + query for the project. + :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) + Object containing suggested refinement settings. + :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions + for the query are retuned by default. + :attr bool highlight: (optional) When `true`, a highlights for the query are + retuned by default. + :attr int count: (optional) The number of document results returned by default. + :attr str sort: (optional) A comma separated list of document fields to sort + results by default. + :attr List[str] return_: (optional) An array of field names to return in + document results if present by default. + """ + + def __init__(self, + *, + collection_ids: List[str] = None, + passages: 'DefaultQueryParamsPassages' = None, + table_results: 'DefaultQueryParamsTableResults' = None, + aggregation: str = None, + suggested_refinements: + 'DefaultQueryParamsSuggestedRefinements' = None, + spelling_suggestions: bool = None, + highlight: bool = None, + count: int = None, + sort: str = None, + return_: List[str] = None) -> None: + """ + Initialize a DefaultQueryParams object. + + :param List[str] collection_ids: (optional) An array of collection + identifiers to query. If empty or omitted all collections in the project + are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :param DefaultQueryParamsTableResults table_results: (optional) Default + project query settings for table results. + :param str aggregation: (optional) A string representing the default + aggregation query for the project. + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: + (optional) Object containing suggested refinement settings. + :param bool spelling_suggestions: (optional) When `true`, a spelling + suggestions for the query are retuned by default. + :param bool highlight: (optional) When `true`, a highlights for the query + are retuned by default. + :param int count: (optional) The number of document results returned by + default. + :param str sort: (optional) A comma separated list of document fields to + sort results by default. + :param List[str] return_: (optional) An array of field names to return in + document results if present by default. + """ + self.collection_ids = collection_ids + self.passages = passages + self.table_results = table_results + self.aggregation = aggregation + self.suggested_refinements = suggested_refinements + self.spelling_suggestions = spelling_suggestions + self.highlight = highlight + self.count = count + self.sort = sort + self.return_ = return_ + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': + """Initialize a DefaultQueryParams object from a json dictionary.""" + args = {} + valid_keys = [ + 'collection_ids', 'passages', 'table_results', 'aggregation', + 'suggested_refinements', 'spelling_suggestions', 'highlight', + 'count', 'sort', 'return_', 'return' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DefaultQueryParams: ' + + ', '.join(bad_keys)) + if 'collection_ids' in _dict: + args['collection_ids'] = _dict.get('collection_ids') + if 'passages' in _dict: + args['passages'] = DefaultQueryParamsPassages._from_dict( + _dict.get('passages')) + if 'table_results' in _dict: + args['table_results'] = DefaultQueryParamsTableResults._from_dict( + _dict.get('table_results')) + if 'aggregation' in _dict: + args['aggregation'] = _dict.get('aggregation') + if 'suggested_refinements' in _dict: + args[ + 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements._from_dict( + _dict.get('suggested_refinements')) + if 'spelling_suggestions' in _dict: + args['spelling_suggestions'] = _dict.get('spelling_suggestions') + if 'highlight' in _dict: + args['highlight'] = _dict.get('highlight') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'sort' in _dict: + args['sort'] = _dict.get('sort') + if 'return' in _dict: + args['return_'] = _dict.get('return') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DefaultQueryParams object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_ids') and self.collection_ids is not None: + _dict['collection_ids'] = self.collection_ids + if hasattr(self, 'passages') and self.passages is not None: + _dict['passages'] = self.passages._to_dict() + if hasattr(self, 'table_results') and self.table_results is not None: + _dict['table_results'] = self.table_results._to_dict() + if hasattr(self, 'aggregation') and self.aggregation is not None: + _dict['aggregation'] = self.aggregation + if hasattr(self, 'suggested_refinements' + ) and self.suggested_refinements is not None: + _dict[ + 'suggested_refinements'] = self.suggested_refinements._to_dict( + ) + if hasattr(self, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'sort') and self.sort is not None: + _dict['sort'] = self.sort + if hasattr(self, 'return_') and self.return_ is not None: + _dict['return'] = self.return_ + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DefaultQueryParams object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DefaultQueryParams') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DefaultQueryParams') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DefaultQueryParamsPassages(): + """ + Default settings configuration for passage search options. + + :attr bool enabled: (optional) When `true`, a passage search is performed by + default. + :attr int count: (optional) The number of passages to return. + :attr List[str] fields: (optional) An array of field names to perfom the passage + search on. + :attr int characters: (optional) The approximate number of characters that each + returned passage will contain. + :attr bool per_document: (optional) When `true` the number of passages that can + be returned from a single document is restricted to the *max_per_document* + value. + :attr int max_per_document: (optional) The default maximum number of passages + that can be taken from a single document as the result of a passage query. + """ + + def __init__(self, + *, + enabled: bool = None, + count: int = None, + fields: List[str] = None, + characters: int = None, + per_document: bool = None, + max_per_document: int = None) -> None: + """ + Initialize a DefaultQueryParamsPassages object. + + :param bool enabled: (optional) When `true`, a passage search is performed + by default. + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perfom the + passage search on. + :param int characters: (optional) The approximate number of characters that + each returned passage will contain. + :param bool per_document: (optional) When `true` the number of passages + that can be returned from a single document is restricted to the + *max_per_document* value. + :param int max_per_document: (optional) The default maximum number of + passages that can be taken from a single document as the result of a + passage query. + """ + self.enabled = enabled + self.count = count + self.fields = fields + self.characters = characters + self.per_document = per_document + self.max_per_document = max_per_document + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + args = {} + valid_keys = [ + 'enabled', 'count', 'fields', 'characters', 'per_document', + 'max_per_document' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DefaultQueryParamsPassages: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + if 'characters' in _dict: + args['characters'] = _dict.get('characters') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') + if 'max_per_document' in _dict: + args['max_per_document'] = _dict.get('max_per_document') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + if hasattr(self, 'characters') and self.characters is not None: + _dict['characters'] = self.characters + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document + if hasattr(self, + 'max_per_document') and self.max_per_document is not None: + _dict['max_per_document'] = self.max_per_document + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DefaultQueryParamsPassages object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DefaultQueryParamsSuggestedRefinements(): + """ + Object containing suggested refinement settings. + + :attr bool enabled: (optional) When `true`, a suggested refinements for the + query are retuned by default. + :attr int count: (optional) The number of suggested refinements to return by + default. + """ + + def __init__(self, *, enabled: bool = None, count: int = None) -> None: + """ + Initialize a DefaultQueryParamsSuggestedRefinements object. + + :param bool enabled: (optional) When `true`, a suggested refinements for + the query are retuned by default. + :param int count: (optional) The number of suggested refinements to return + by default. + """ + self.enabled = enabled + self.count = count + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + args = {} + valid_keys = ['enabled', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DefaultQueryParamsSuggestedRefinements: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Collection') -> bool: + def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Completions(): +class DefaultQueryParamsTableResults(): """ - An object containing an array of autocompletion suggestions. + Default project query settings for table results. - :attr List[str] completions: (optional) Array of autcomplete suggestion based on - the provided prefix. + :attr bool enabled: (optional) When `true`, a table results for the query are + retuned by default. + :attr int count: (optional) The number of table results to return by default. + :attr int per_document: (optional) The number of table results to include in + each result document. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__(self, + *, + enabled: bool = None, + count: int = None, + per_document: int = None) -> None: """ - Initialize a Completions object. + Initialize a DefaultQueryParamsTableResults object. - :param List[str] completions: (optional) Array of autcomplete suggestion - based on the provided prefix. + :param bool enabled: (optional) When `true`, a table results for the query + are retuned by default. + :param int count: (optional) The number of table results to return by + default. + :param int per_document: (optional) The number of table results to include + in each result document. """ - self.completions = completions + self.enabled = enabled + self.count = count + self.per_document = per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - valid_keys = ['completions'] + valid_keys = ['enabled', 'count', 'per_document'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Completions: ' + 'Unrecognized keys detected in dictionary for class DefaultQueryParamsTableResults: ' + ', '.join(bad_keys)) - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Completions object from a json dictionary.""" + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'completions') and self.completions is not None: - _dict['completions'] = self.completions + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document return _dict def _to_dict(self): @@ -1101,98 +2928,241 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Completions object.""" + """Return a `str` version of this DefaultQueryParamsTableResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Completions') -> bool: + def __eq__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Completions') -> bool: + def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsAggregation(): +class DeleteDocumentResponse(): """ - Display settings for aggregations. + Information returned when a document is deleted. - :attr str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :attr str label: (optional) User-friendly alias for the aggregation. - :attr bool multiple_selections_allowed: (optional) Whether users is allowed to - select more than one of the aggregation terms. - :attr str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :attr str document_id: (optional) The unique identifier of the document. + :attr str status: (optional) Status of the document. A deleted document has the + status deleted. + """ + + def __init__(self, *, document_id: str = None, status: str = None) -> None: + """ + Initialize a DeleteDocumentResponse object. + + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document + has the status deleted. + """ + self.document_id = document_id + self.status = status + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': + """Initialize a DeleteDocumentResponse object from a json dictionary.""" + args = {} + valid_keys = ['document_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteDocumentResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DeleteDocumentResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DeleteDocumentResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(Enum): + """ + Status of the document. A deleted document has the status deleted. + """ + DELETED = "deleted" + + +class DocumentAccepted(): + """ + Information returned after an uploaded document is accepted. + + :attr str document_id: (optional) The unique identifier of the ingested + document. + :attr str status: (optional) Status of the document in the ingestion process. A + status of `processing` is returned for documents that are ingested with a + *version* date before `2019-01-01`. The `pending` status is returned for all + others. + """ + + def __init__(self, *, document_id: str = None, status: str = None) -> None: + """ + Initialize a DocumentAccepted object. + + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion + process. A status of `processing` is returned for documents that are + ingested with a *version* date before `2019-01-01`. The `pending` status is + returned for all others. + """ + self.document_id = document_id + self.status = status + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': + """Initialize a DocumentAccepted object from a json dictionary.""" + args = {} + valid_keys = ['document_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAccepted object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this DocumentAccepted object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DocumentAccepted') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'DocumentAccepted') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(Enum): + """ + Status of the document in the ingestion process. A status of `processing` is + returned for documents that are ingested with a *version* date before + `2019-01-01`. The `pending` status is returned for all others. + """ + PROCESSING = "processing" + PENDING = "pending" + + +class DocumentAttribute(): + """ + List of document attributes. + + :attr str type: (optional) The type of attribute. + :attr str text: (optional) The text associated with the attribute. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. """ def __init__(self, *, - name: str = None, - label: str = None, - multiple_selections_allowed: bool = None, - visualization_type: str = None) -> None: + type: str = None, + text: str = None, + location: 'TableElementLocation' = None) -> None: """ - Initialize a ComponentSettingsAggregation object. + Initialize a DocumentAttribute object. - :param str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :param str label: (optional) User-friendly alias for the aggregation. - :param bool multiple_selections_allowed: (optional) Whether users is - allowed to select more than one of the aggregation terms. - :param str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. """ - self.name = name - self.label = label - self.multiple_selections_allowed = multiple_selections_allowed - self.visualization_type = visualization_type + self.type = type + self.text = text + self.location = location @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': + """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'label', 'multiple_selections_allowed', 'visualization_type' - ] + valid_keys = ['type', 'text', 'location'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsAggregation: ' + 'Unrecognized keys detected in dictionary for class DocumentAttribute: ' + ', '.join(bad_keys)) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'multiple_selections_allowed' in _dict: - args['multiple_selections_allowed'] = _dict.get( - 'multiple_selections_allowed') - if 'visualization_type' in _dict: - args['visualization_type'] = _dict.get('visualization_type') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + """Initialize a DocumentAttribute object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'multiple_selections_allowed' - ) and self.multiple_selections_allowed is not None: - _dict[ - 'multiple_selections_allowed'] = self.multiple_selections_allowed - if hasattr( - self, - 'visualization_type') and self.visualization_type is not None: - _dict['visualization_type'] = self.visualization_type + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() return _dict def _to_dict(self): @@ -1200,80 +3170,96 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsAggregation object.""" + """Return a `str` version of this DocumentAttribute object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: + def __eq__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: + def __ne__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class VisualizationTypeEnum(Enum): - """ - Type of visualization to use when rendering the aggregation. - """ - AUTO = "auto" - FACET_TABLE = "facet_table" - WORD_CLOUD = "word_cloud" - MAP = "map" - -class ComponentSettingsFieldsShown(): +class Enrichment(): """ - Fields shown in the results section of the UI. - - :attr ComponentSettingsFieldsShownBody body: (optional) Body label. - :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + Information about a specific enrichment. + + :attr str enrichment_id: (optional) The unique identifier of this enrichment. + :attr str name: (optional) The human readable name for this enrichment. + :attr str description: (optional) The description of this enrichment. + :attr str type: (optional) The type of this enrichment. + :attr EnrichmentOptions options: (optional) A object containing options for the + current enrichment. """ def __init__(self, *, - body: 'ComponentSettingsFieldsShownBody' = None, - title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + enrichment_id: str = None, + name: str = None, + description: str = None, + type: str = None, + options: 'EnrichmentOptions' = None) -> None: """ - Initialize a ComponentSettingsFieldsShown object. + Initialize a Enrichment object. - :param ComponentSettingsFieldsShownBody body: (optional) Body label. - :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param str enrichment_id: (optional) The unique identifier of this + enrichment. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. + :param EnrichmentOptions options: (optional) A object containing options + for the current enrichment. """ - self.body = body - self.title = title + self.enrichment_id = enrichment_id + self.name = name + self.description = description + self.type = type + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Enrichment': + """Initialize a Enrichment object from a json dictionary.""" args = {} - valid_keys = ['body', 'title'] + valid_keys = ['enrichment_id', 'name', 'description', 'type', 'options'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShown: ' + 'Unrecognized keys detected in dictionary for class Enrichment: ' + ', '.join(bad_keys)) - if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody._from_dict( - _dict.get('body')) - if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle._from_dict( - _dict.get('title')) + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'options' in _dict: + args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + """Initialize a Enrichment object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body._to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title._to_dict() + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options._to_dict() return _dict def _to_dict(self): @@ -1281,66 +3267,117 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShown object.""" + """Return a `str` version of this Enrichment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __eq__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __ne__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of this enrichment. + """ + PART_OF_SPEECH = "part_of_speech" + SENTIMENT = "sentiment" + NATURAL_LANGUAGE_UNDERSTANDING = "natural_language_understanding" + DICTIONARY = "dictionary" + REGULAR_EXPRESSION = "regular_expression" + UIMA_ANNOTATOR = "uima_annotator" + RULE_BASED = "rule_based" + WATSON_KNOWLEDGE_STUDIO_MODEL = "watson_knowledge_studio_model" -class ComponentSettingsFieldsShownBody(): - """ - Body label. - :attr bool use_passage: (optional) Use the whole passage as the body. - :attr str field: (optional) Use a specific field as the title. +class EnrichmentOptions(): + """ + A object containing options for the current enrichment. + + :attr List[str] languages: (optional) An array of supported languages for this + enrichment. + :attr str entity_type: (optional) The type of entity. Required when creating + `dictionary` and `regular_expression` **type** enrichment. Not valid when + creating any other type of enrichment. + :attr str regular_expression: (optional) The regular expression to apply for + this enrichment. Required only when the **type** of enrichment being created is + a `regular_expression`. Not valid when creating any other type of enrichment. + :attr str result_field: (optional) The name of the result document field that + this enrichment creates. Required only when the enrichment **type** is + `rule_based`. Not valid when creating any other type of enrichment. """ - def __init__(self, *, use_passage: bool = None, field: str = None) -> None: - """ - Initialize a ComponentSettingsFieldsShownBody object. - - :param bool use_passage: (optional) Use the whole passage as the body. - :param str field: (optional) Use a specific field as the title. - """ - self.use_passage = use_passage - self.field = field + def __init__(self, + *, + languages: List[str] = None, + entity_type: str = None, + regular_expression: str = None, + result_field: str = None) -> None: + """ + Initialize a EnrichmentOptions object. + + :param List[str] languages: (optional) An array of supported languages for + this enrichment. + :param str entity_type: (optional) The type of entity. Required when + creating `dictionary` and `regular_expression` **type** enrichment. Not + valid when creating any other type of enrichment. + :param str regular_expression: (optional) The regular expression to apply + for this enrichment. Required only when the **type** of enrichment being + created is a `regular_expression`. Not valid when creating any other type + of enrichment. + :param str result_field: (optional) The name of the result document field + that this enrichment creates. Required only when the enrichment **type** is + `rule_based`. Not valid when creating any other type of enrichment. + """ + self.languages = languages + self.entity_type = entity_type + self.regular_expression = regular_expression + self.result_field = result_field @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': + """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - valid_keys = ['use_passage', 'field'] + valid_keys = [ + 'languages', 'entity_type', 'regular_expression', 'result_field' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownBody: ' + 'Unrecognized keys detected in dictionary for class EnrichmentOptions: ' + ', '.join(bad_keys)) - if 'use_passage' in _dict: - args['use_passage'] = _dict.get('use_passage') - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'languages' in _dict: + args['languages'] = _dict.get('languages') + if 'entity_type' in _dict: + args['entity_type'] = _dict.get('entity_type') + if 'regular_expression' in _dict: + args['regular_expression'] = _dict.get('regular_expression') + if 'result_field' in _dict: + args['result_field'] = _dict.get('result_field') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + """Initialize a EnrichmentOptions object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'use_passage') and self.use_passage is not None: - _dict['use_passage'] = self.use_passage - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'languages') and self.languages is not None: + _dict['languages'] = self.languages + if hasattr(self, 'entity_type') and self.entity_type is not None: + _dict['entity_type'] = self.entity_type + if hasattr( + self, + 'regular_expression') and self.regular_expression is not None: + _dict['regular_expression'] = self.regular_expression + if hasattr(self, 'result_field') and self.result_field is not None: + _dict['result_field'] = self.result_field return _dict def _to_dict(self): @@ -1348,59 +3385,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + """Return a `str` version of this EnrichmentOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __eq__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __ne__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownTitle(): +class Enrichments(): """ - Title label. + An object containing an array of enrichment definitions. - :attr str field: (optional) Use a specific field as the title. + :attr List[Enrichment] enrichments: (optional) An array of enrichment + definitions. """ - def __init__(self, *, field: str = None) -> None: + def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: """ - Initialize a ComponentSettingsFieldsShownTitle object. + Initialize a Enrichments object. - :param str field: (optional) Use a specific field as the title. + :param List[Enrichment] enrichments: (optional) An array of enrichment + definitions. """ - self.field = field + self.enrichments = enrichments @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Enrichments': + """Initialize a Enrichments object from a json dictionary.""" args = {} - valid_keys = ['field'] + valid_keys = ['enrichments'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownTitle: ' + 'Unrecognized keys detected in dictionary for class Enrichments: ' + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'enrichments' in _dict: + args['enrichments'] = [ + Enrichment._from_dict(x) for x in (_dict.get('enrichments')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + """Initialize a Enrichments object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'enrichments') and self.enrichments is not None: + _dict['enrichments'] = [x._to_dict() for x in self.enrichments] return _dict def _to_dict(self): @@ -1408,110 +3449,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" + """Return a `str` version of this Enrichments object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __eq__(self, other: 'Enrichments') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __ne__(self, other: 'Enrichments') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsResponse(): +class Field(): """ - A response containing the default component settings. + Object containing field details. - :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the - results section of the UI. - :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. - :attr bool structured_search: (optional) Whether or not structured search is - enabled. - :attr int results_per_page: (optional) Number or results shown per page. - :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of - component setting aggregations. + :attr str field: (optional) The name of the field. + :attr str type: (optional) The type of the field. + :attr str collection_id: (optional) The collection Id of the collection where + the field was found. """ - def __init__( - self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None) -> None: + def __init__(self, + *, + field: str = None, + type: str = None, + collection_id: str = None) -> None: """ - Initialize a ComponentSettingsResponse object. + Initialize a Field object. - :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown - in the results section of the UI. - :param bool autocomplete: (optional) Whether or not autocomplete is - enabled. - :param bool structured_search: (optional) Whether or not structured search - is enabled. - :param int results_per_page: (optional) Number or results shown per page. - :param List[ComponentSettingsAggregation] aggregations: (optional) a list - of component setting aggregations. + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. + :param str collection_id: (optional) The collection Id of the collection + where the field was found. """ - self.fields_shown = fields_shown - self.autocomplete = autocomplete - self.structured_search = structured_search - self.results_per_page = results_per_page - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': - """Initialize a ComponentSettingsResponse object from a json dictionary.""" - args = {} - valid_keys = [ - 'fields_shown', 'autocomplete', 'structured_search', - 'results_per_page', 'aggregations' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsResponse: ' - + ', '.join(bad_keys)) - if 'fields_shown' in _dict: - args['fields_shown'] = ComponentSettingsFieldsShown._from_dict( - _dict.get('fields_shown')) - if 'autocomplete' in _dict: - args['autocomplete'] = _dict.get('autocomplete') - if 'structured_search' in _dict: - args['structured_search'] = _dict.get('structured_search') - if 'results_per_page' in _dict: - args['results_per_page'] = _dict.get('results_per_page') - if 'aggregations' in _dict: - args['aggregations'] = [ - ComponentSettingsAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] + self.field = field + self.type = type + self.collection_id = collection_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Field': + """Initialize a Field object from a json dictionary.""" + args = {} + valid_keys = ['field', 'type', 'collection_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Field: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + """Initialize a Field object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'fields_shown') and self.fields_shown is not None: - _dict['fields_shown'] = self.fields_shown._to_dict() - if hasattr(self, 'autocomplete') and self.autocomplete is not None: - _dict['autocomplete'] = self.autocomplete - if hasattr(self, - 'structured_search') and self.structured_search is not None: - _dict['structured_search'] = self.structured_search - if hasattr(self, - 'results_per_page') and self.results_per_page is not None: - _dict['results_per_page'] = self.results_per_page - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id return _dict def _to_dict(self): @@ -1519,68 +3529,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsResponse object.""" + """Return a `str` version of this Field object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsResponse') -> bool: + def __eq__(self, other: 'Field') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsResponse') -> bool: + def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of the field. + """ + NESTED = "nested" + STRING = "string" + DATE = "date" + LONG = "long" + INTEGER = "integer" + SHORT = "short" + BYTE = "byte" + DOUBLE = "double" + FLOAT = "float" + BOOLEAN = "boolean" + BINARY = "binary" + -class DeleteDocumentResponse(): +class ListCollectionsResponse(): """ - Information returned when a document is deleted. + Response object containing an array of collection details. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the - status deleted. + :attr List[Collection] collections: (optional) An array containing information + about each collection in the project. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__(self, *, collections: List['Collection'] = None) -> None: """ - Initialize a DeleteDocumentResponse object. + Initialize a ListCollectionsResponse object. - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. + :param List[Collection] collections: (optional) An array containing + information about each collection in the project. """ - self.document_id = document_id - self.status = status + self.collections = collections @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': + """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status'] + valid_keys = ['collections'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' + 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' + ', '.join(bad_keys)) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if 'collections' in _dict: + args['collections'] = [ + Collection._from_dict(x) for x in (_dict.get('collections')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + """Initialize a ListCollectionsResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'collections') and self.collections is not None: + _dict['collections'] = [x._to_dict() for x in self.collections] return _dict def _to_dict(self): @@ -1588,80 +3609,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DeleteDocumentResponse object.""" + """Return a `str` version of this ListCollectionsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DeleteDocumentResponse') -> bool: + def __eq__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DeleteDocumentResponse') -> bool: + def __ne__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - DELETED = "deleted" - -class DocumentAccepted(): +class ListFieldsResponse(): """ - Information returned after an uploaded document is accepted. + The list of fetched fields. + The fields are returned using a fully qualified name format, however, the format + differs slightly from that used by the query operations. + * Fields which contain nested objects are assigned a type of "nested". + * Fields which belong to a nested object are prefixed with `.properties` (for + example, `warnings.properties.severity` means that the `warnings` object has a + property called `severity`). - :attr str document_id: (optional) The unique identifier of the ingested - document. - :attr str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. + :attr List[Field] fields: (optional) An array containing information about each + field in the collections. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__(self, *, fields: List['Field'] = None) -> None: """ - Initialize a DocumentAccepted object. + Initialize a ListFieldsResponse object. - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. + :param List[Field] fields: (optional) An array containing information about + each field in the collections. """ - self.document_id = document_id - self.status = status + self.fields = fields @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': + """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status'] + valid_keys = ['fields'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' + 'Unrecognized keys detected in dictionary for class ListFieldsResponse: ' + ', '.join(bad_keys)) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if 'fields' in _dict: + args['fields'] = [ + Field._from_dict(x) for x in (_dict.get('fields')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAccepted object from a json dictionary.""" + """Initialize a ListFieldsResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = [x._to_dict() for x in self.fields] return _dict def _to_dict(self): @@ -1669,91 +3679,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAccepted object.""" + """Return a `str` version of this ListFieldsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DocumentAccepted') -> bool: + def __eq__(self, other: 'ListFieldsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DocumentAccepted') -> bool: + def __ne__(self, other: 'ListFieldsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): - """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. - """ - PROCESSING = "processing" - PENDING = "pending" - -class DocumentAttribute(): +class ListProjectsResponse(): """ - List of document attributes. + A list of projects in this instance. - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr TableElementLocation location: (optional) The numeric location of the - identified element in the document, represented with two integers labeled - `begin` and `end`. + :attr List[ProjectListDetails] projects: (optional) An array of project details. """ - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: """ - Initialize a DocumentAttribute object. + Initialize a ListProjectsResponse object. - :param str type: (optional) The type of attribute. - :param str text: (optional) The text associated with the attribute. - :param TableElementLocation location: (optional) The numeric location of - the identified element in the document, represented with two integers - labeled `begin` and `end`. + :param List[ProjectListDetails] projects: (optional) An array of project + details. """ - self.type = type - self.text = text - self.location = location + self.projects = projects @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': - """Initialize a DocumentAttribute object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': + """Initialize a ListProjectsResponse object from a json dictionary.""" args = {} - valid_keys = ['type', 'text', 'location'] + valid_keys = ['projects'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAttribute: ' + 'Unrecognized keys detected in dictionary for class ListProjectsResponse: ' + ', '.join(bad_keys)) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( - _dict.get('location')) + if 'projects' in _dict: + args['projects'] = [ + ProjectListDetails._from_dict(x) + for x in (_dict.get('projects')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAttribute object from a json dictionary.""" + """Initialize a ListProjectsResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + if hasattr(self, 'projects') and self.projects is not None: + _dict['projects'] = [x._to_dict() for x in self.projects] return _dict def _to_dict(self): @@ -1761,79 +3743,152 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAttribute object.""" + """Return a `str` version of this ListProjectsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DocumentAttribute') -> bool: + def __eq__(self, other: 'ListProjectsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DocumentAttribute') -> bool: + def __ne__(self, other: 'ListProjectsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Field(): +class Notice(): """ - Object containing field details. + A notice produced for the collection. - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. - :attr str collection_id: (optional) The collection Id of the collection where - the field was found. + :attr str notice_id: (optional) Identifies the notice. Many notices might have + the same ID. This field exists so that user applications can programmatically + identify a notice and take automatic corrective action. Typical notice IDs + include: `index_failed`, `index_failed_too_many_requests`, + `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, + `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, + `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a complete + list, other values might be returned. + :attr datetime created: (optional) The creation date of the collection in the + format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :attr str document_id: (optional) Unique identifier of the document. + :attr str collection_id: (optional) Unique identifier of the collection. + :attr str query_id: (optional) Unique identifier of the query used for relevance + training. + :attr str severity: (optional) Severity level of the notice. + :attr str step: (optional) Ingestion or training step in which the notice + occurred. + :attr str description: (optional) The description of the notice. """ def __init__(self, *, - field: str = None, - type: str = None, - collection_id: str = None) -> None: + notice_id: str = None, + created: datetime = None, + document_id: str = None, + collection_id: str = None, + query_id: str = None, + severity: str = None, + step: str = None, + description: str = None) -> None: """ - Initialize a Field object. + Initialize a Notice object. - :param str field: (optional) The name of the field. - :param str type: (optional) The type of the field. - :param str collection_id: (optional) The collection Id of the collection - where the field was found. + :param str notice_id: (optional) Identifies the notice. Many notices might + have the same ID. This field exists so that user applications can + programmatically identify a notice and take automatic corrective action. + Typical notice IDs include: `index_failed`, + `index_failed_too_many_requests`, `index_failed_incompatible_field`, + `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, + `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a + complete list, other values might be returned. + :param datetime created: (optional) The creation date of the collection in + the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param str document_id: (optional) Unique identifier of the document. + :param str collection_id: (optional) Unique identifier of the collection. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice + occurred. + :param str description: (optional) The description of the notice. """ - self.field = field - self.type = type + self.notice_id = notice_id + self.created = created + self.document_id = document_id self.collection_id = collection_id + self.query_id = query_id + self.severity = severity + self.step = step + self.description = description @classmethod - def from_dict(cls, _dict: Dict) -> 'Field': - """Initialize a Field object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Notice': + """Initialize a Notice object from a json dictionary.""" args = {} - valid_keys = ['field', 'type', 'collection_id'] + valid_keys = [ + 'notice_id', 'created', 'document_id', 'collection_id', 'query_id', + 'severity', 'step', 'description' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Field: ' + + 'Unrecognized keys detected in dictionary for class Notice: ' + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') + if 'notice_id' in _dict: + args['notice_id'] = _dict.get('notice_id') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') + if 'query_id' in _dict: + args['query_id'] = _dict.get('query_id') + if 'severity' in _dict: + args['severity'] = _dict.get('severity') + if 'step' in _dict: + args['step'] = _dict.get('step') + if 'description' in _dict: + args['description'] = _dict.get('description') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Field object from a json dictionary.""" + """Initialize a Notice object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + if hasattr(self, 'notice_id') and self.notice_id is not None: + _dict['notice_id'] = self.notice_id + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id + if hasattr(self, 'query_id') and self.query_id is not None: + _dict['query_id'] = self.query_id + if hasattr(self, 'severity') and self.severity is not None: + _dict['severity'] = self.severity + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description return _dict def _to_dict(self): @@ -1841,79 +3896,128 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Field object.""" + """Return a `str` version of this Notice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Field') -> bool: + def __eq__(self, other: 'Notice') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Field') -> bool: + def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class SeverityEnum(Enum): """ - The type of the field. + Severity level of the notice. """ - NESTED = "nested" - STRING = "string" - DATE = "date" - LONG = "long" - INTEGER = "integer" - SHORT = "short" - BYTE = "byte" - DOUBLE = "double" - FLOAT = "float" - BOOLEAN = "boolean" - BINARY = "binary" + WARNING = "warning" + ERROR = "error" -class ListCollectionsResponse(): +class ProjectDetails(): """ - Response object containing an array of collection details. - - :attr List[Collection] collections: (optional) An array containing information - about each collection in the project. + Detailed information about the specified project. + + :attr str project_id: (optional) The unique identifier of this project. + :attr str name: (optional) The human readable name of this project. + :attr str type: (optional) The project type of this project. + :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :attr int collection_count: (optional) The number of collections configured in + this project. + :attr DefaultQueryParams default_query_parameters: (optional) Default query + parameters for this project. """ - def __init__(self, *, collections: List['Collection'] = None) -> None: - """ - Initialize a ListCollectionsResponse object. - - :param List[Collection] collections: (optional) An array containing - information about each collection in the project. - """ - self.collections = collections + def __init__(self, + *, + project_id: str = None, + name: str = None, + type: str = None, + relevancy_training_status: + 'ProjectListDetailsRelevancyTrainingStatus' = None, + collection_count: int = None, + default_query_parameters: 'DefaultQueryParams' = None) -> None: + """ + Initialize a ProjectDetails object. + + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The project type of this project. + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :param int collection_count: (optional) The number of collections + configured in this project. + :param DefaultQueryParams default_query_parameters: (optional) Default + query parameters for this project. + """ + self.project_id = project_id + self.name = name + self.type = type + self.relevancy_training_status = relevancy_training_status + self.collection_count = collection_count + self.default_query_parameters = default_query_parameters @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': - """Initialize a ListCollectionsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProjectDetails': + """Initialize a ProjectDetails object from a json dictionary.""" args = {} - valid_keys = ['collections'] + valid_keys = [ + 'project_id', 'name', 'type', 'relevancy_training_status', + 'collection_count', 'default_query_parameters' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' + 'Unrecognized keys detected in dictionary for class ProjectDetails: ' + ', '.join(bad_keys)) - if 'collections' in _dict: - args['collections'] = [ - Collection._from_dict(x) for x in (_dict.get('collections')) - ] + if 'project_id' in _dict: + args['project_id'] = _dict.get('project_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'relevancy_training_status' in _dict: + args[ + 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus._from_dict( + _dict.get('relevancy_training_status')) + if 'collection_count' in _dict: + args['collection_count'] = _dict.get('collection_count') + if 'default_query_parameters' in _dict: + args['default_query_parameters'] = DefaultQueryParams._from_dict( + _dict.get('default_query_parameters')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListCollectionsResponse object from a json dictionary.""" + """Initialize a ProjectDetails object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x._to_dict() for x in self.collections] + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'relevancy_training_status' + ) and self.relevancy_training_status is not None: + _dict[ + 'relevancy_training_status'] = self.relevancy_training_status._to_dict( + ) + if hasattr(self, + 'collection_count') and self.collection_count is not None: + _dict['collection_count'] = self.collection_count + if hasattr(self, 'default_query_parameters' + ) and self.default_query_parameters is not None: + _dict[ + 'default_query_parameters'] = self.default_query_parameters._to_dict( + ) return _dict def _to_dict(self): @@ -1921,69 +4025,116 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListCollectionsResponse object.""" + """Return a `str` version of this ProjectDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ListCollectionsResponse') -> bool: + def __eq__(self, other: 'ProjectDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListCollectionsResponse') -> bool: + def __ne__(self, other: 'ProjectDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The project type of this project. + """ + DOCUMENT_RETRIEVAL = "document_retrieval" + ANSWER_RETRIEVAL = "answer_retrieval" + CONTENT_MINING = "content_mining" + OTHER = "other" + -class ListFieldsResponse(): +class ProjectListDetails(): """ - The list of fetched fields. - The fields are returned using a fully qualified name format, however, the format - differs slightly from that used by the query operations. - * Fields which contain nested objects are assigned a type of "nested". - * Fields which belong to a nested object are prefixed with `.properties` (for - example, `warnings.properties.severity` means that the `warnings` object has a - property called `severity`). - - :attr List[Field] fields: (optional) An array containing information about each - field in the collections. + Details about a specific project. + + :attr str project_id: (optional) The unique identifier of this project. + :attr str name: (optional) The human readable name of this project. + :attr str type: (optional) The project type of this project. + :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :attr int collection_count: (optional) The number of collections configured in + this project. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__(self, + *, + project_id: str = None, + name: str = None, + type: str = None, + relevancy_training_status: + 'ProjectListDetailsRelevancyTrainingStatus' = None, + collection_count: int = None) -> None: """ - Initialize a ListFieldsResponse object. + Initialize a ProjectListDetails object. - :param List[Field] fields: (optional) An array containing information about - each field in the collections. + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The project type of this project. + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :param int collection_count: (optional) The number of collections + configured in this project. """ - self.fields = fields + self.project_id = project_id + self.name = name + self.type = type + self.relevancy_training_status = relevancy_training_status + self.collection_count = collection_count @classmethod - def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': - """Initialize a ListFieldsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProjectListDetails': + """Initialize a ProjectListDetails object from a json dictionary.""" args = {} - valid_keys = ['fields'] + valid_keys = [ + 'project_id', 'name', 'type', 'relevancy_training_status', + 'collection_count' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ListFieldsResponse: ' + 'Unrecognized keys detected in dictionary for class ProjectListDetails: ' + ', '.join(bad_keys)) - if 'fields' in _dict: - args['fields'] = [ - Field._from_dict(x) for x in (_dict.get('fields')) - ] + if 'project_id' in _dict: + args['project_id'] = _dict.get('project_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'relevancy_training_status' in _dict: + args[ + 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus._from_dict( + _dict.get('relevancy_training_status')) + if 'collection_count' in _dict: + args['collection_count'] = _dict.get('collection_count') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListFieldsResponse object from a json dictionary.""" + """Initialize a ProjectListDetails object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x._to_dict() for x in self.fields] + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'relevancy_training_status' + ) and self.relevancy_training_status is not None: + _dict[ + 'relevancy_training_status'] = self.relevancy_training_status._to_dict( + ) + if hasattr(self, + 'collection_count') and self.collection_count is not None: + _dict['collection_count'] = self.collection_count return _dict def _to_dict(self): @@ -1991,152 +4142,159 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListFieldsResponse object.""" + """Return a `str` version of this ProjectListDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ListFieldsResponse') -> bool: + def __eq__(self, other: 'ProjectListDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListFieldsResponse') -> bool: + def __ne__(self, other: 'ProjectListDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - -class Notice(): - """ - A notice produced for the collection. - - :attr str notice_id: (optional) Identifies the notice. Many notices might have - the same ID. This field exists so that user applications can programmatically - identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, - `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, - `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, - `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a complete - list, other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str collection_id: (optional) Unique identifier of the collection. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice - occurred. - :attr str description: (optional) The description of the notice. + class TypeEnum(Enum): + """ + The project type of this project. + """ + DOCUMENT_RETRIEVAL = "document_retrieval" + ANSWER_RETRIEVAL = "answer_retrieval" + CONTENT_MINING = "content_mining" + OTHER = "other" + + +class ProjectListDetailsRelevancyTrainingStatus(): + """ + Relevancy training status information for this project. + + :attr str data_updated: (optional) When the training data was updated. + :attr int total_examples: (optional) The total number of examples. + :attr bool sufficient_label_diversity: (optional) When `true`, sufficent label + diversity is present to allow training for this project. + :attr bool processing: (optional) When `true`, the relevancy training is in + processing. + :attr bool minimum_examples_added: (optional) When `true`, the minimum number of + examples required to train has been met. + :attr str successfully_trained: (optional) The time that the most recent + successful training occured. + :attr bool available: (optional) When `true`, relevancy training is available + when querying collections in the project. + :attr int notices: (optional) The number of notices generated during the + relevancy training. + :attr bool minimum_queries_added: (optional) When `true`, the minimum number of + queries required to train has been met. """ def __init__(self, *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - collection_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: - """ - Initialize a Notice object. - - :param str notice_id: (optional) Identifies the notice. Many notices might - have the same ID. This field exists so that user applications can - programmatically identify a notice and take automatic corrective action. - Typical notice IDs include: `index_failed`, - `index_failed_too_many_requests`, `index_failed_incompatible_field`, - `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, - `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a - complete list, other values might be returned. - :param datetime created: (optional) The creation date of the collection in - the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str document_id: (optional) Unique identifier of the document. - :param str collection_id: (optional) Unique identifier of the collection. - :param str query_id: (optional) Unique identifier of the query used for - relevance training. - :param str severity: (optional) Severity level of the notice. - :param str step: (optional) Ingestion or training step in which the notice - occurred. - :param str description: (optional) The description of the notice. - """ - self.notice_id = notice_id - self.created = created - self.document_id = document_id - self.collection_id = collection_id - self.query_id = query_id - self.severity = severity - self.step = step - self.description = description + data_updated: str = None, + total_examples: int = None, + sufficient_label_diversity: bool = None, + processing: bool = None, + minimum_examples_added: bool = None, + successfully_trained: str = None, + available: bool = None, + notices: int = None, + minimum_queries_added: bool = None) -> None: + """ + Initialize a ProjectListDetailsRelevancyTrainingStatus object. + + :param str data_updated: (optional) When the training data was updated. + :param int total_examples: (optional) The total number of examples. + :param bool sufficient_label_diversity: (optional) When `true`, sufficent + label diversity is present to allow training for this project. + :param bool processing: (optional) When `true`, the relevancy training is + in processing. + :param bool minimum_examples_added: (optional) When `true`, the minimum + number of examples required to train has been met. + :param str successfully_trained: (optional) The time that the most recent + successful training occured. + :param bool available: (optional) When `true`, relevancy training is + available when querying collections in the project. + :param int notices: (optional) The number of notices generated during the + relevancy training. + :param bool minimum_queries_added: (optional) When `true`, the minimum + number of queries required to train has been met. + """ + self.data_updated = data_updated + self.total_examples = total_examples + self.sufficient_label_diversity = sufficient_label_diversity + self.processing = processing + self.minimum_examples_added = minimum_examples_added + self.successfully_trained = successfully_trained + self.available = available + self.notices = notices + self.minimum_queries_added = minimum_queries_added @classmethod - def from_dict(cls, _dict: Dict) -> 'Notice': - """Initialize a Notice object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProjectListDetailsRelevancyTrainingStatus': + """Initialize a ProjectListDetailsRelevancyTrainingStatus object from a json dictionary.""" args = {} valid_keys = [ - 'notice_id', 'created', 'document_id', 'collection_id', 'query_id', - 'severity', 'step', 'description' + 'data_updated', 'total_examples', 'sufficient_label_diversity', + 'processing', 'minimum_examples_added', 'successfully_trained', + 'available', 'notices', 'minimum_queries_added' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Notice: ' + - ', '.join(bad_keys)) - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') + 'Unrecognized keys detected in dictionary for class ProjectListDetailsRelevancyTrainingStatus: ' + + ', '.join(bad_keys)) + if 'data_updated' in _dict: + args['data_updated'] = _dict.get('data_updated') + if 'total_examples' in _dict: + args['total_examples'] = _dict.get('total_examples') + if 'sufficient_label_diversity' in _dict: + args['sufficient_label_diversity'] = _dict.get( + 'sufficient_label_diversity') + if 'processing' in _dict: + args['processing'] = _dict.get('processing') + if 'minimum_examples_added' in _dict: + args['minimum_examples_added'] = _dict.get('minimum_examples_added') + if 'successfully_trained' in _dict: + args['successfully_trained'] = _dict.get('successfully_trained') + if 'available' in _dict: + args['available'] = _dict.get('available') + if 'notices' in _dict: + args['notices'] = _dict.get('notices') + if 'minimum_queries_added' in _dict: + args['minimum_queries_added'] = _dict.get('minimum_queries_added') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Notice object from a json dictionary.""" + """Initialize a ProjectListDetailsRelevancyTrainingStatus object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'notice_id') and self.notice_id is not None: - _dict['notice_id'] = self.notice_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'severity') and self.severity is not None: - _dict['severity'] = self.severity - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description + if hasattr(self, 'data_updated') and self.data_updated is not None: + _dict['data_updated'] = self.data_updated + if hasattr(self, 'total_examples') and self.total_examples is not None: + _dict['total_examples'] = self.total_examples + if hasattr(self, 'sufficient_label_diversity' + ) and self.sufficient_label_diversity is not None: + _dict[ + 'sufficient_label_diversity'] = self.sufficient_label_diversity + if hasattr(self, 'processing') and self.processing is not None: + _dict['processing'] = self.processing + if hasattr(self, 'minimum_examples_added' + ) and self.minimum_examples_added is not None: + _dict['minimum_examples_added'] = self.minimum_examples_added + if hasattr(self, 'successfully_trained' + ) and self.successfully_trained is not None: + _dict['successfully_trained'] = self.successfully_trained + if hasattr(self, 'available') and self.available is not None: + _dict['available'] = self.available + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = self.notices + if hasattr(self, 'minimum_queries_added' + ) and self.minimum_queries_added is not None: + _dict['minimum_queries_added'] = self.minimum_queries_added return _dict def _to_dict(self): @@ -2144,26 +4302,21 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Notice object.""" + """Return a `str` version of this ProjectListDetailsRelevancyTrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Notice') -> bool: + def __eq__(self, + other: 'ProjectListDetailsRelevancyTrainingStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Notice') -> bool: + def __ne__(self, + other: 'ProjectListDetailsRelevancyTrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class SeverityEnum(Enum): - """ - Severity level of the notice. - """ - WARNING = "warning" - ERROR = "error" - class QueryAggregation(): """ @@ -2249,6 +4402,7 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping['average'] = 'QueryCalculationAggregation' mapping['unique_count'] = 'QueryCalculationAggregation' mapping['top_hits'] = 'QueryTopHitsAggregation' + mapping['group_by'] = 'QueryGroupByAggregation' disc_value = _dict.get('type') if disc_value is None: raise ValueError( @@ -2264,6 +4418,140 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) +class QueryGroupByAggregationResult(): + """ + Top value result for the term aggregation. + + :attr str key: Value of the field with a non-zero frequency in the document set. + :attr int matching_results: Number of documents containing the 'key'. + :attr float relevancy: (optional) The relevancy for this group. + :attr int total_matching_documents: (optional) The number of documents which + have the group as the value of specified field in the whole set of documents in + this collection. Returned only when the `relevancy` parameter is set to `true`. + :attr int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned only + when the `relevancy` parameter is set to `true`. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, + key: str, + matching_results: int, + *, + relevancy: float = None, + total_matching_documents: int = None, + estimated_matching_documents: int = None, + aggregations: List['QueryAggregation'] = None) -> None: + """ + Initialize a QueryGroupByAggregationResult object. + + :param str key: Value of the field with a non-zero frequency in the + document set. + :param int matching_results: Number of documents containing the 'key'. + :param float relevancy: (optional) The relevancy for this group. + :param int total_matching_documents: (optional) The number of documents + which have the group as the value of specified field in the whole set of + documents in this collection. Returned only when the `relevancy` parameter + is set to `true`. + :param int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned + only when the `relevancy` parameter is set to `true`. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.key = key + self.matching_results = matching_results + self.relevancy = relevancy + self.total_matching_documents = total_matching_documents + self.estimated_matching_documents = estimated_matching_documents + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': + """Initialize a QueryGroupByAggregationResult object from a json dictionary.""" + args = {} + valid_keys = [ + 'key', 'matching_results', 'relevancy', 'total_matching_documents', + 'estimated_matching_documents', 'aggregations' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryGroupByAggregationResult: ' + + ', '.join(bad_keys)) + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryGroupByAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryGroupByAggregationResult JSON' + ) + if 'relevancy' in _dict: + args['relevancy'] = _dict.get('relevancy') + if 'total_matching_documents' in _dict: + args['total_matching_documents'] = _dict.get( + 'total_matching_documents') + if 'estimated_matching_documents' in _dict: + args['estimated_matching_documents'] = _dict.get( + 'estimated_matching_documents') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryGroupByAggregationResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'relevancy') and self.relevancy is not None: + _dict['relevancy'] = self.relevancy + if hasattr(self, 'total_matching_documents' + ) and self.total_matching_documents is not None: + _dict['total_matching_documents'] = self.total_matching_documents + if hasattr(self, 'estimated_matching_documents' + ) and self.estimated_matching_documents is not None: + _dict[ + 'estimated_matching_documents'] = self.estimated_matching_documents + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryGroupByAggregationResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryGroupByAggregationResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryGroupByAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryHistogramAggregationResult(): """ Histogram numeric interval result. @@ -2371,8 +4659,8 @@ class QueryLargePassages(): :attr List[str] fields: (optional) A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :attr int count: (optional) The maximum number of passages to return. The search - returns fewer passages if the requested total is not found. The default is `10`. - The maximum is `100`. + returns fewer passages if the requested total is not found. The maximum is + `100`. :attr int characters: (optional) The approximate number of characters that any one passage will have. """ @@ -2399,7 +4687,7 @@ def __init__(self, included. :param int count: (optional) The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The - default is `10`. The maximum is `100`. + maximum is `100`. :param int characters: (optional) The approximate number of characters that any one passage will have. """ @@ -2485,7 +4773,7 @@ class QueryLargeSuggestedRefinements(): :attr bool enabled: (optional) Whether to perform suggested refinements. :attr int count: (optional) Maximum number of suggested refinements texts to be - returned. The default is `10`. The maximum is `100`. + returned. The maximum is `100`. """ def __init__(self, *, enabled: bool = None, count: int = None) -> None: @@ -2494,7 +4782,7 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: :param bool enabled: (optional) Whether to perform suggested refinements. :param int count: (optional) Maximum number of suggested refinements texts - to be returned. The default is `10`. The maximum is `100`. + to be returned. The maximum is `100`. """ self.enabled = enabled self.count = count @@ -3340,6 +5628,13 @@ class QueryTermAggregationResult(): :attr str key: Value of the field with a non-zero frequency in the document set. :attr int matching_results: Number of documents containing the 'key'. + :attr float relevancy: (optional) The relevancy for this term. + :attr int total_matching_documents: (optional) The number of documents which + have the term as the value of specified field in the whole set of documents in + this collection. Returned only when the `relevancy` parameter is set to `true`. + :attr int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned only + when the `relevancy` parameter is set to `true`. :attr List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ @@ -3348,6 +5643,9 @@ def __init__(self, key: str, matching_results: int, *, + relevancy: float = None, + total_matching_documents: int = None, + estimated_matching_documents: int = None, aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a QueryTermAggregationResult object. @@ -3355,18 +5653,32 @@ def __init__(self, :param str key: Value of the field with a non-zero frequency in the document set. :param int matching_results: Number of documents containing the 'key'. + :param float relevancy: (optional) The relevancy for this term. + :param int total_matching_documents: (optional) The number of documents + which have the term as the value of specified field in the whole set of + documents in this collection. Returned only when the `relevancy` parameter + is set to `true`. + :param int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned + only when the `relevancy` parameter is set to `true`. :param List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ self.key = key self.matching_results = matching_results + self.relevancy = relevancy + self.total_matching_documents = total_matching_documents + self.estimated_matching_documents = estimated_matching_documents self.aggregations = aggregations @classmethod def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['key', 'matching_results', 'aggregations'] + valid_keys = [ + 'key', 'matching_results', 'relevancy', 'total_matching_documents', + 'estimated_matching_documents', 'aggregations' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -3384,6 +5696,14 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': raise ValueError( 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' ) + if 'relevancy' in _dict: + args['relevancy'] = _dict.get('relevancy') + if 'total_matching_documents' in _dict: + args['total_matching_documents'] = _dict.get( + 'total_matching_documents') + if 'estimated_matching_documents' in _dict: + args['estimated_matching_documents'] = _dict.get( + 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation._from_dict(x) @@ -3404,6 +5724,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results + if hasattr(self, 'relevancy') and self.relevancy is not None: + _dict['relevancy'] = self.relevancy + if hasattr(self, 'total_matching_documents' + ) and self.total_matching_documents is not None: + _dict['total_matching_documents'] = self.total_matching_documents + if hasattr(self, 'estimated_matching_documents' + ) and self.estimated_matching_documents is not None: + _dict[ + 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict @@ -5816,6 +8145,86 @@ def __ne__(self, other: 'QueryFilterAggregation') -> bool: return not self == other +class QueryGroupByAggregation(QueryAggregation): + """ + Returns the top values for the field specified. + + :attr List[QueryGroupByAggregationResult] results: (optional) Array of top + values for the field. + """ + + def __init__(self, + type: str, + *, + results: List['QueryGroupByAggregationResult'] = None) -> None: + """ + Initialize a QueryGroupByAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param List[QueryGroupByAggregationResult] results: (optional) Array of top + values for the field. + """ + self.type = type + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': + """Initialize a QueryGroupByAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryGroupByAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryGroupByAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryGroupByAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryGroupByAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryGroupByAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryGroupByAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryGroupByAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryHistogramAggregation(QueryAggregation): """ Numeric interval segments to categorize documents by using field values from a single diff --git a/test/integration/test_discovery_v2.py b/test/integration/test_discovery_v2.py new file mode 100644 index 000000000..03779a640 --- /dev/null +++ b/test/integration/test_discovery_v2.py @@ -0,0 +1,110 @@ +# coding: utf-8 +from unittest import TestCase +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +from ibm_watson.discovery_v2 import CreateEnrichment, EnrichmentOptions +import os +import ibm_watson +import pytest + + +@pytest.mark.skipif(os.getenv('TEST_DISCO_V2') is None, + reason='only test in cpd and prem') +class Discoveryv2(TestCase): + discovery = None + project_id = 'f0b9920b-caa8-4b89-abf7-e250989eee5a' # This project is created for integration testing + collection_id = None + collection_name = 'python_test_collection' + + @classmethod + def setup_class(cls): + authenticator = IAMAuthenticator('apikey') + cls.discovery = ibm_watson.DiscoveryV2( + version='2020-08-12', + authenticator=authenticator + ) + cls.discovery.set_service_url('url') + cls.discovery.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + collections = cls.discovery.list_collections( + cls.project_id).get_result()['collections'] + for collection in collections: + if collection['name'] == cls.collection_name: + cls.collection_id = collection['collection_id'] + + if cls.collection_id is None: + print("Creating a new temporary collection") + cls.collection_id = cls.discovery.create_collection( + cls.project_id, + cls.collection_name, + description="Integration test for python sdk").get_result( + )['collection_id'] + + @classmethod + def teardown_class(cls): + collections = cls.discovery.list_collections( + cls.project_id).get_result()['collections'] + for collection in collections: + if collection['name'] == cls.collection_name: + print('Deleting the temporary collection') + cls.discovery.delete_collection(cls.project_id, + cls.collection_id) + break + + def test_projects(self): + projs = self.discovery.list_projects().get_result() + assert projs is not None + proj = self.discovery.get_project( + self.project_id).get_result() + assert proj is not None + + def test_collections(self): + cols = self.discovery.list_collections(self.project_id).get_result() + assert cols is not None + col = self.discovery.get_collection( + self.project_id, + self.collection_id + ).get_result() + assert col is not None + + def test_enrichments(self): + enrs = self.discovery.list_enrichments(self.project_id).get_result() + print(enrs) + assert enrs is not None + + enrichmentOptions = EnrichmentOptions( + languages=["en"], + entity_type="keyword" + ) + enrichment = CreateEnrichment( + name="python test enrichment", + description="test enrichment", + type="dictionary", + options=enrichmentOptions + ) + with open(os.path.join(os.path.dirname(__file__), '../../resources/TestEnrichments.csv'), 'r') as fileinfo: + enr = self.discovery.create_enrichment( + project_id=self.project_id, + enrichment=enrichment._to_dict(), + file=fileinfo + ).get_result() + assert enr is not None + enrichment_id = enr["enrichment_id"] + enrichment = self.discovery.get_enrichment( + self.project_id, + enrichment_id + ).get_result() + assert enrichment is not None + enr = self.discovery.update_enrichment( + project_id=self.project_id, + enrichment_id=enrichment_id, + name="python test enrichment", + description="updated description" + ).get_result() + assert enr is not None + self.discovery.delete_enrichment( + self.project_id, + enrichment_id + ) From 9ef3c6e2df323a2bb7403bef417ddbd34ca6b462 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:28:21 -0400 Subject: [PATCH 4/7] feat: regenrate all services using current api def --- ibm_watson/assistant_v1.py | 141 ++------------- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/discovery_v1.py | 2 +- ibm_watson/natural_language_classifier_v1.py | 2 +- .../natural_language_understanding_v1.py | 71 ++++---- ibm_watson/personality_insights_v3.py | 2 +- ibm_watson/speech_to_text_v1.py | 161 +++++++++++++----- ibm_watson/text_to_speech_v1.py | 29 +++- ibm_watson/tone_analyzer_v3.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- 11 files changed, 200 insertions(+), 216 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index a8f34d5f9..e6bac2d3e 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -41,7 +41,7 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'assistant' def __init__( @@ -100,7 +100,6 @@ def message(self, API offers significant advantages, including ease of deployment, automatic state management, versioning, and search capabilities. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-api-overview). - There is no rate limit for this operation. :param str workspace_id: Unique identifier of the workspace. :param MessageInput input: (optional) An input object that includes the @@ -189,8 +188,6 @@ def list_workspaces(self, List workspaces. List the workspaces associated with a Watson Assistant service instance. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param int page_limit: (optional) The number of records to return in each page of results. @@ -251,8 +248,6 @@ def create_workspace(self, Create a workspace based on component objects. You must provide workspace components defining the content of the new workspace. - This operation is limited to 30 requests per 30 minutes. For more information, see - **Rate limiting**. :param str name: (optional) The name of the workspace. This string cannot contain carriage return, newline, or tab characters. @@ -340,9 +335,6 @@ def get_workspace(self, Get information about a workspace. Get information about a workspace, optionally including all workspace content. - With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. - With **export**=`true`, the limit is 20 requests per 30 minutes. For more - information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param bool export: (optional) Whether to include all element content in @@ -409,8 +401,6 @@ def update_workspace(self, Update an existing workspace with new or modified data. You must provide component objects defining the content of the updated workspace. - This operation is limited to 30 request per 30 minutes. For more information, see - **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str name: (optional) The name of the workspace. This string cannot @@ -509,8 +499,6 @@ def delete_workspace(self, workspace_id: str, Delete workspace. Delete a workspace from the service instance. - This operation is limited to 30 requests per 30 minutes. For more information, see - **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param dict headers: A `dict` containing the request headers @@ -557,9 +545,6 @@ def list_intents(self, List intents. List the intents for a workspace. - With **export**=`false`, this operation is limited to 2000 requests per 30 - minutes. With **export**=`true`, the limit is 400 requests per 30 minutes. For - more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param bool export: (optional) Whether to include all element content in @@ -624,8 +609,6 @@ def create_intent(self, Create a new intent. If you want to create multiple intents with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 2000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The name of the intent. This string must conform to the @@ -689,9 +672,6 @@ def get_intent(self, Get intent. Get information about an intent, optionally including all intent content. - With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. - With **export**=`true`, the limit is 400 requests per 30 minutes. For more - information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -752,8 +732,6 @@ def update_intent(self, objects defining the content of the updated intent. If you want to update multiple intents with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 2000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -826,8 +804,6 @@ def delete_intent(self, workspace_id: str, intent: str, Delete intent. Delete an intent from a workspace. - This operation is limited to 2000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -879,8 +855,6 @@ def list_examples(self, List the user input examples for an intent, optionally including contextual entity mentions. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -943,8 +917,6 @@ def create_example(self, Add a new user input example to an intent. If you want to add multiple examples with a single API call, consider using the **[Update intent](#update-intent)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1004,8 +976,6 @@ def get_example(self, Get user input example. Get information about a user input example. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1059,8 +1029,6 @@ def update_example(self, Update the text of a user input example. If you want to update multiple examples with a single API call, consider using the **[Update intent](#update-intent)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1116,8 +1084,6 @@ def delete_example(self, workspace_id: str, intent: str, text: str, Delete user input example. Delete a user input example from an intent. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1171,8 +1137,6 @@ def list_counterexamples(self, List the counterexamples for a workspace. Counterexamples are examples that have been marked as irrelevant input. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param int page_limit: (optional) The number of records to return in each @@ -1231,8 +1195,6 @@ def create_counterexample(self, been marked as irrelevant input. If you want to add multiple counterexamples with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input marked as irrelevant input. This @@ -1285,8 +1247,6 @@ def get_counterexample(self, Get information about a counterexample. Counterexamples are examples that have been marked as irrelevant input. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input counterexample (for example, @@ -1335,10 +1295,6 @@ def update_counterexample(self, Update the text of a counterexample. Counterexamples are examples that have been marked as irrelevant input. - If you want to update multiple counterexamples with a single API call, consider - using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input counterexample (for example, @@ -1389,8 +1345,6 @@ def delete_counterexample(self, workspace_id: str, text: str, Delete a counterexample from a workspace. Counterexamples are examples that have been marked as irrelevant input. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input counterexample (for example, @@ -1442,9 +1396,6 @@ def list_entities(self, List entities. List the entities for a workspace. - With **export**=`false`, this operation is limited to 1000 requests per 30 - minutes. With **export**=`true`, the limit is 200 requests per 30 minutes. For - more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param bool export: (optional) Whether to include all element content in @@ -1511,8 +1462,6 @@ def create_entity(self, Create a new entity, or enable a system entity. If you want to create multiple entities with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. This string must conform to the @@ -1583,9 +1532,6 @@ def get_entity(self, Get entity. Get information about an entity, optionally including all entity content. - With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. - With **export**=`true`, the limit is 200 requests per 30 minutes. For more - information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1648,8 +1594,6 @@ def update_entity(self, objects defining the content of the updated entity. If you want to update multiple entities with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1727,8 +1671,6 @@ def delete_entity(self, workspace_id: str, entity: str, Delete entity. Delete an entity from a workspace, or disable a system entity. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1778,8 +1720,6 @@ def list_mentions(self, List mentions for a contextual entity. An entity mention is an occurrence of a contextual entity in the context of an intent user input example. - This operation is limited to 200 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1841,8 +1781,6 @@ def list_values(self, List entity values. List the values for an entity. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1913,8 +1851,6 @@ def create_value(self, Create a new value for an entity. If you want to create multiple entity values with a single API call, consider using the **[Update entity](#update-entity)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1990,8 +1926,6 @@ def get_value(self, Get entity value. Get information about an entity value. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2058,8 +1992,6 @@ def update_value(self, component objects defining the content of the updated entity value. If you want to update multiple entity values with a single API call, consider using the **[Update entity](#update-entity)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2145,8 +2077,6 @@ def delete_value(self, workspace_id: str, entity: str, value: str, Delete entity value. Delete a value from an entity. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2201,8 +2131,6 @@ def list_synonyms(self, List entity value synonyms. List the synonyms for an entity value. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2269,8 +2197,6 @@ def create_synonym(self, If you want to create multiple synonyms with a single API call, consider using the **[Update entity](#update-entity)** or **[Update entity value](#update-entity-value)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2330,8 +2256,6 @@ def get_synonym(self, Get entity value synonym. Get information about a synonym of an entity value. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2389,8 +2313,6 @@ def update_synonym(self, If you want to update multiple synonyms with a single API call, consider using the **[Update entity](#update-entity)** or **[Update entity value](#update-entity-value)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2445,8 +2367,6 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, Delete entity value synonym. Delete a synonym from an entity value. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2502,8 +2422,6 @@ def list_dialog_nodes(self, List dialog nodes. List the dialog nodes for a workspace. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param int page_limit: (optional) The number of records to return in each @@ -2579,8 +2497,6 @@ def create_dialog_node(self, Create a new dialog node. If you want to create multiple dialog nodes with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID. This string must conform to the @@ -2696,8 +2612,6 @@ def get_dialog_node(self, Get dialog node. Get information about a dialog node. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). @@ -2764,8 +2678,6 @@ def update_dialog_node(self, Update an existing dialog node with new or modified data. If you want to update multiple dialog nodes with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). @@ -2879,8 +2791,6 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, Delete dialog node. Delete a dialog node from a workspace. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). @@ -2930,9 +2840,6 @@ def list_logs(self, List log events in a workspace. List the events from the log of a specific workspace. - If **cursor** is not specified, this operation is limited to 40 requests per 30 - minutes. If **cursor** is specified, the limit is 120 requests per minute. For - more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str sort: (optional) How to sort the returned log events. You can @@ -2990,9 +2897,6 @@ def list_all_logs(self, List log events in all workspaces. List the events from the logs of all workspaces in the service instance. - If **cursor** is not specified, this operation is limited to 40 requests per 30 - minutes. If **cursor** is specified, the limit is 120 requests per minute. For - more information, see **Rate limiting**. :param str filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that @@ -3055,8 +2959,6 @@ def delete_user_data(self, customer_id: str, with a request that passes data. For more information about personal data and customer IDs, see [Information security](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security). - This operation is limited to 4 requests per minute. For more information, see - **Rate limiting**. :param str customer_id: The customer ID for which all data is to be deleted. @@ -4748,8 +4650,7 @@ class DialogNodeOutputGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is available only for Plus and - Premium users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is used only by the v2 runtime API. :attr List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :attr str selection_policy: (optional) How a response is selected from the list, @@ -4816,8 +4717,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is available only for Plus and - Premium users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is used only by the v2 runtime + API. :param List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. @@ -5003,8 +4904,7 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is available only for Plus and - Premium users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is used only by the v2 runtime API. """ TEXT = "text" PAUSE = "pause" @@ -5680,10 +5580,8 @@ class DialogSuggestionResponseGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. The - **search_skill** response type is available only for Plus and Premium users, and - is used only by the v2 runtime API. + **Note:** The **search_skill** response type is is used only by the v2 runtime + API. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during @@ -5724,10 +5622,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. The - **search_skill** response type is available only for Plus and Premium - users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is is used only by the v2 + runtime API. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event @@ -5865,10 +5761,8 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Plus and Premium users. The **search_skill** response - type is available only for Plus and Premium users, and is used only by the v2 - runtime API. + **Note:** The **search_skill** response type is is used only by the v2 runtime + API. """ TEXT = "text" PAUSE = "pause" @@ -8765,8 +8659,6 @@ class RuntimeResponseGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during @@ -8787,8 +8679,6 @@ class RuntimeResponseGeneric(): the dialog node's **title** property. :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, - which is only available for Plus and Premium users. """ def __init__(self, @@ -8812,8 +8702,6 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event @@ -8836,8 +8724,6 @@ def __init__(self, :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation - feature, which is only available for Plus and Premium users. """ self.response_type = response_type self.text = text @@ -8964,8 +8850,6 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Plus and Premium users. """ TEXT = "text" PAUSE = "pause" @@ -9939,7 +9823,6 @@ class WorkspaceSystemSettings(): related to the Watson Assistant user interface. :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace settings related to the disambiguation feature. - **Note:** This feature is available only to Plus and Premium users. :attr dict human_agent_assist: (optional) For internal use only. :attr bool spelling_suggestions: (optional) Whether spelling correction is enabled for the workspace. @@ -9972,7 +9855,6 @@ def __init__( settings related to the Watson Assistant user interface. :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace settings related to the disambiguation feature. - **Note:** This feature is available only to Plus and Premium users. :param dict human_agent_assist: (optional) For internal use only. :param bool spelling_suggestions: (optional) Whether spelling correction is enabled for the workspace. @@ -10083,7 +9965,6 @@ def __ne__(self, other: 'WorkspaceSystemSettings') -> bool: class WorkspaceSystemSettingsDisambiguation(): """ Workspace settings related to the disambiguation feature. - **Note:** This feature is available only to Plus and Premium users. :attr str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 85ef86f45..82f5bf54d 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -40,7 +40,7 @@ class CompareComplyV1(BaseService): """The Compare Comply V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/compare-comply/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'compare_comply' def __init__( diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 2fa04f3b4..7894a3c55 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -45,7 +45,7 @@ class DiscoveryV1(BaseService): """The Discovery V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/discovery/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.discovery.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'discovery' def __init__( diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 5441a6f68..77c43d7f7 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -41,7 +41,7 @@ class NaturalLanguageClassifierV1(BaseService): """The Natural Language Classifier V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'natural_language_classifier' def __init__( diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 22ee86f76..d778867c0 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -44,7 +44,7 @@ class NaturalLanguageUnderstandingV1(BaseService): """The Natural Language Understanding V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'natural-language-understanding' def __init__( @@ -110,7 +110,7 @@ def analyze(self, - Relations - Semantic roles - Sentiment - - Syntax (Experimental). + - Syntax. If a language for the input text is not specified with the `language` parameter, the service [automatically detects the language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages). @@ -123,9 +123,8 @@ def analyze(self, :param str url: (optional) The webpage to analyze. One of the `text`, `html`, or `url` parameters is required. :param bool clean: (optional) Set this to `false` to disable webpage - cleaning. To learn more about webpage cleaning, see the [Analyzing - webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages) - documentation. + cleaning. For more information about webpage cleaning, see [Analyzing + webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages). :param str xpath: (optional) An [XPath query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) to perform on `html` or `url` input. Results of the query will be appended @@ -137,10 +136,9 @@ def analyze(self, analyzed text. :param str language: (optional) ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support - differs depending on the features you include in your analysis. See - [Language - support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support) - for more information. + differs depending on the features you include in your analysis. For more + information, see [Language + support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support). :param int limit_text_characters: (optional) Sets the maximum number of characters that are processed by the service. :param dict headers: A `dict` containing the request headers @@ -872,9 +870,8 @@ class CategoriesResult(): A categorization of the analyzed text. :attr str label: (optional) The path to the category through the 5-level - taxonomy hierarchy. For the complete list of categories, see the [Categories - hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) - documentation. + taxonomy hierarchy. For more information about the categories, see [Categories + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). :attr float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. :attr CategoriesResultExplanation explanation: (optional) Information that helps @@ -890,10 +887,9 @@ def __init__(self, Initialize a CategoriesResult object. :param str label: (optional) The path to the category through the 5-level - taxonomy hierarchy. For the complete list of categories, see the + taxonomy hierarchy. For more information about the categories, see [Categories - hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) - documentation. + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. :param CategoriesResultExplanation explanation: (optional) Information that @@ -1713,8 +1709,8 @@ def __ne__(self, other: 'EmotionScores') -> bool: class EntitiesOptions(): """ - Identifies people, cities, organizations, and other entities in the content. See - [Entity types and + Identifies people, cities, organizations, and other entities in the content. For more + information, see [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through @@ -2133,7 +2129,8 @@ class Features(): entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. :attr EntitiesOptions entities: (optional) Identifies people, cities, - organizations, and other entities in the content. See [Entity types and + organizations, and other entities in the content. For more information, see + [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported @@ -2147,8 +2144,8 @@ class Features(): and publication date. Supports URL and HTML input types only. :attr RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` - relation might connect the entities "Nobel Prize" and "Albert Einstein". See - [Relation + relation might connect the entities "Nobel Prize" and "Albert Einstein". For + more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also @@ -2197,7 +2194,8 @@ def __init__(self, `keywords.emotion`. Supported languages: English. :param EntitiesOptions entities: (optional) Identifies people, cities, - organizations, and other entities in the content. See [Entity types and + organizations, and other entities in the content. For more information, see + [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are @@ -2212,7 +2210,7 @@ def __init__(self, :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert - Einstein". See [Relation + Einstein". For more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also @@ -2696,7 +2694,7 @@ class Model(): :attr str status: (optional) When the status is `available`, the model is ready to use. :attr str model_id: (optional) Unique model ID. - :attr str language: (optional) ISO 639-1 code indicating the language of the + :attr str language: (optional) ISO 639-1 code that indicates the language of the model. :attr str description: (optional) Model description. :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace @@ -2728,8 +2726,8 @@ def __init__(self, :param str status: (optional) When the status is `available`, the model is ready to use. :param str model_id: (optional) Unique model ID. - :param str language: (optional) ISO 639-1 code indicating the language of - the model. + :param str language: (optional) ISO 639-1 code that indicates the language + of the model. :param str description: (optional) Model description. :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. @@ -2833,6 +2831,17 @@ def __ne__(self, other: 'Model') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + When the status is `available`, the model is ready to use. + """ + STARTING = "starting" + TRAINING = "training" + DEPLOYING = "deploying" + AVAILABLE = "available" + ERROR = "error" + DELETED = "deleted" + class RelationArgument(): """ @@ -2988,7 +2997,7 @@ class RelationsOptions(): """ Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert - Einstein". See [Relation + Einstein". For more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. @@ -4351,8 +4360,8 @@ class TokenResult(): TokenResult. :attr str text: (optional) The token as it appears in the analyzed text. - :attr str part_of_speech: (optional) The part of speech of the token. For - descriptions of the values, see [Universal Dependencies POS + :attr str part_of_speech: (optional) The part of speech of the token. For more + information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). :attr List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. @@ -4371,7 +4380,7 @@ def __init__(self, :param str text: (optional) The token as it appears in the analyzed text. :param str part_of_speech: (optional) The part of speech of the token. For - descriptions of the values, see [Universal Dependencies POS + more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). :param List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. @@ -4441,8 +4450,8 @@ def __ne__(self, other: 'TokenResult') -> bool: class PartOfSpeechEnum(Enum): """ - The part of speech of the token. For descriptions of the values, see [Universal - Dependencies POS tags](https://universaldependencies.org/u/pos/). + The part of speech of the token. For more information about the values, see + [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). """ ADJ = "ADJ" ADP = "ADP" diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 7ba3c2986..d964df64b 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -51,7 +51,7 @@ class PersonalityInsightsV3(BaseService): """The Personality Insights V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/personality-insights/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'personality_insights' def __init__( diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index e23fa4e1a..f1cabb45a 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -14,12 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -The IBM® Speech to Text service provides APIs that use IBM's speech-recognition -capabilities to produce transcripts of spoken audio. The service can transcribe speech -from various languages and audio formats. In addition to basic transcription, the service -can produce detailed information about many different aspects of the audio. For most -languages, the service supports two sampling rates, broadband and narrowband. It returns -all JSON response content in the UTF-8 character set. +The IBM Watson™ Speech to Text service provides APIs that use IBM's +speech-recognition capabilities to produce transcripts of spoken audio. The service can +transcribe speech from various languages and audio formats. In addition to basic +transcription, the service can produce detailed information about many different aspects +of the audio. For most languages, the service supports two sampling rates, broadband and +narrowband. It returns all JSON response content in the UTF-8 character set. For speech recognition, the service supports synchronous and asynchronous HTTP Representational State Transfer (REST) interfaces. It also supports a WebSocket interface that provides a full-duplex, low-latency communication channel: Clients send requests and @@ -53,7 +53,7 @@ class SpeechToTextV1(BaseService): """The Speech to Text V1 service.""" - DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/speech-to-text/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'speech_to_text' def __init__( @@ -86,7 +86,8 @@ def list_models(self, **kwargs) -> 'DetailedResponse': Lists all language models that are available for use with the service. The information includes the name of the model and its minimum sampling rate in Hertz, - among other things. + among other things. The ordering of the list of models can change from call to + call; do not rely on an alphabetized or static list of models. **See also:** [Languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). @@ -358,11 +359,9 @@ def recognize(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, German, Japanese, Korean, and Spanish - (both broadband and narrowband models) and UK English (narrowband model) - transcription only. To determine whether a language model supports speaker - labels, you can also use the **Get a model** method and check that the - attribute `speaker_labels` is set to `true`. + **Note:** Applies to US English, Australian English, German, Japanese, + Korean, and Spanish (both broadband and narrowband models) and UK English + (narrowband model) transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the @@ -512,9 +511,9 @@ def register_callback(self, Register a callback. Registers a callback URL with the service for use with subsequent asynchronous - recognition requests. The service attempts to register, or white-list, the - callback URL if it is not already registered by sending a `GET` request to the - callback URL. The service passes a random alphanumeric challenge string via the + recognition requests. The service attempts to register, or allowlist, the callback + URL if it is not already registered by sending a `GET` request to the callback + URL. The service passes a random alphanumeric challenge string via the `challenge_string` parameter of the request. The request includes an `Accept` header that specifies `text/plain` as the required response type. To be registered successfully, the callback URL must respond to the `GET` request @@ -524,9 +523,9 @@ def register_callback(self, registration request with response code 201. The service sends only a single `GET` request to the callback URL. If the service does not receive a reply with a response code of 200 and a body that echoes the - challenge string sent by the service within five seconds, it does not white-list + challenge string sent by the service within five seconds, it does not allowlist the URL; it instead sends status code 400 in response to the **Register a - callback** request. If the requested callback URL is already white-listed, the + callback** request. If the requested callback URL is already allowlisted, the service responds to the initial registration request with response code 200. If you specify a user secret with the request, the service uses it as a key to calculate an HMAC-SHA1 signature of the challenge string in its response to the @@ -542,7 +541,7 @@ def register_callback(self, URL](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#register). :param str callback_url: An HTTP or HTTPS URL to which callback - notifications are to be sent. To be white-listed, the URL must successfully + notifications are to be sent. To be allowlisted, the URL must successfully echo the challenge string during URL verification. During verification, the client can also check the signature that the service sends in the `X-Callback-Signature` header to verify the origin of the request. @@ -584,7 +583,7 @@ def unregister_callback(self, callback_url: str, """ Unregister a callback. - Unregisters a callback URL that was previously white-listed with a **Register a + Unregisters a callback URL that was previously allowlisted with a **Register a callback** request for use with the asynchronous interface. Once unregistered, the URL can no longer be used with asynchronous recognition requests. **See also:** [Unregistering a callback @@ -746,7 +745,7 @@ def create_job(self, for the recognition request. See [Languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). :param str callback_url: (optional) A URL to which callback notifications - are to be sent. The URL must already be successfully white-listed by using + are to be sent. The URL must already be successfully allowlisted by using the **Register a callback** method. You can include the same callback URL with any number of job creation requests. Omit the parameter to poll the service for job completion and results. @@ -884,11 +883,9 @@ def create_job(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, German, Japanese, Korean, and Spanish - (both broadband and narrowband models) and UK English (narrowband model) - transcription only. To determine whether a language model supports speaker - labels, you can also use the **Get a model** method and check that the - attribute `speaker_labels` is set to `true`. + **Note:** Applies to US English, Australian English, German, Japanese, + Korean, and Spanish (both broadband and narrowband models) and UK English + (narrowband model) transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the @@ -1277,9 +1274,11 @@ def list_language_models(self, models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). :param str language: (optional) The identifier of the language for which - custom language or custom acoustic models are to be returned (for example, - `en-US`). Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. + custom language or custom acoustic models are to be returned. Omit the + parameter to see all custom language or custom acoustic models that are + owned by the requesting credentials. **Note:** The `ar-AR` (Modern Standard + Arabic) and `zh-CN` (Mandarin Chinese) languages are not available for + language model customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2540,9 +2539,11 @@ def list_acoustic_models(self, models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). :param str language: (optional) The identifier of the language for which - custom language or custom acoustic models are to be returned (for example, - `en-US`). Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. + custom language or custom acoustic models are to be returned. Omit the + parameter to see all custom language or custom acoustic models that are + owned by the requesting credentials. **Note:** The `ar-AR` (Modern Standard + Arabic) and `zh-CN` (Mandarin Chinese) languages are not available for + language model customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3212,9 +3213,14 @@ def delete_user_data(self, customer_id: str, deletes all data for the customer ID, regardless of the method by which the information was added. The method has no effect if no data is associated with the customer ID. You must issue the request with credentials for the same instance of - the service that was used to associate the customer ID with the data. - You associate a customer ID with data by passing the `X-Watson-Metadata` header - with a request that passes the data. + the service that was used to associate the customer ID with the data. You + associate a customer ID with data by passing the `X-Watson-Metadata` header with a + request that passes the data. + **Note:** If you delete an instance of the service from the service console, all + data associated with that service instance is automatically deleted. This includes + all custom language models, corpora, grammars, and words; all custom acoustic + models and audio resources; all registered endpoints for the asynchronous HTTP + interface; and all data related to speech recognition requests. **See also:** [Information security](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-information-security#information-security). @@ -3258,6 +3264,8 @@ class ModelId(Enum): AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3324,6 +3332,8 @@ class Model(Enum): AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3390,6 +3400,8 @@ class Model(Enum): AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3448,6 +3460,35 @@ class Events(Enum): RECOGNITIONS_FAILED = 'recognitions.failed' +class ListLanguageModelsEnums(object): + + class Language(Enum): + """ + The identifier of the language for which custom language or custom acoustic models + are to be returned. Omit the parameter to see all custom language or custom + acoustic models that are owned by the requesting credentials. **Note:** The + `ar-AR` (Modern Standard Arabic) and `zh-CN` (Mandarin Chinese) languages are not + available for language model customization. + """ + AR_AR = 'ar-AR' + DE_DE = 'de-DE' + EN_GB = 'en-GB' + EN_US = 'en-US' + ES_AR = 'es-AR' + ES_ES = 'es-ES' + ES_CL = 'es-CL' + ES_CO = 'es-CO' + ES_MX = 'es-MX' + ES_PE = 'es-PE' + FR_FR = 'fr-FR' + IT_IT = 'it-IT' + JA_JP = 'ja-JP' + KO_KR = 'ko-KR' + NL_NL = 'nl-NL' + PT_BR = 'pt-BR' + ZH_CN = 'zh-CN' + + class TrainLanguageModelEnums(object): class WordTypeToAdd(Enum): @@ -3508,6 +3549,35 @@ class ContentType(Enum): APPLICATION_SRGS_XML = 'application/srgs+xml' +class ListAcousticModelsEnums(object): + + class Language(Enum): + """ + The identifier of the language for which custom language or custom acoustic models + are to be returned. Omit the parameter to see all custom language or custom + acoustic models that are owned by the requesting credentials. **Note:** The + `ar-AR` (Modern Standard Arabic) and `zh-CN` (Mandarin Chinese) languages are not + available for language model customization. + """ + AR_AR = 'ar-AR' + DE_DE = 'de-DE' + EN_GB = 'en-GB' + EN_US = 'en-US' + ES_AR = 'es-AR' + ES_ES = 'es-ES' + ES_CL = 'es-CL' + ES_CO = 'es-CO' + ES_MX = 'es-MX' + ES_PE = 'es-PE' + FR_FR = 'fr-FR' + IT_IT = 'it-IT' + JA_JP = 'ja-JP' + KO_KR = 'ko-KR' + NL_NL = 'nl-NL' + PT_BR = 'pt-BR' + ZH_CN = 'zh-CN' + + class AddAudioEnums(object): class ContentType(Enum): @@ -6397,9 +6467,9 @@ class RegisterStatus(): recognition. :attr str status: The current status of the job: - * `created`: The service successfully white-listed the callback URL as a result + * `created`: The service successfully allowlisted the callback URL as a result of the call. - * `already created`: The URL was already white-listed. + * `already created`: The URL was already allowlisted. :attr str url: The callback URL that is successfully registered. """ @@ -6408,9 +6478,9 @@ def __init__(self, status: str, url: str) -> None: Initialize a RegisterStatus object. :param str status: The current status of the job: - * `created`: The service successfully white-listed the callback URL as a + * `created`: The service successfully allowlisted the callback URL as a result of the call. - * `already created`: The URL was already white-listed. + * `already created`: The URL was already allowlisted. :param str url: The callback URL that is successfully registered. """ self.status = status @@ -6474,9 +6544,9 @@ def __ne__(self, other: 'RegisterStatus') -> bool: class StatusEnum(Enum): """ The current status of the job: - * `created`: The service successfully white-listed the callback URL as a result of + * `created`: The service successfully allowlisted the callback URL as a result of the call. - * `already created`: The URL was already white-listed. + * `already created`: The URL was already allowlisted. """ CREATED = "created" ALREADY_CREATED = "already created" @@ -7290,6 +7360,10 @@ class SupportedFeatures(): can be used to create a custom language model based on the language model. :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. + **Note:** The field returns `true` for all models. However, speaker labels are + supported only for US English, Australian English, German, Japanese, Korean, and + Spanish (both broadband and narrowband models) and UK English (narrowband model + only). Speaker labels are not supported for any other models. """ def __init__(self, custom_language_model: bool, @@ -7302,6 +7376,11 @@ def __init__(self, custom_language_model: bool, language model. :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. + **Note:** The field returns `true` for all models. However, speaker labels + are supported only for US English, Australian English, German, Japanese, + Korean, and Spanish (both broadband and narrowband models) and UK English + (narrowband model only). Speaker labels are not supported for any other + models. """ self.custom_language_model = custom_language_model self.speaker_labels = speaker_labels diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 6fb28a941..1fd76b89e 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -The IBM® Text to Speech service provides APIs that use IBM's speech-synthesis +The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, dialects, and voices. The service supports at least one male or female voice, sometimes both, for each language. The audio is streamed back to the client with minimal delay. @@ -50,7 +50,7 @@ class TextToSpeechV1(BaseService): """The Text to Speech V1 service.""" - DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/text-to-speech/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'text_to_speech' def __init__( @@ -82,8 +82,10 @@ def list_voices(self, **kwargs) -> 'DetailedResponse': List voices. Lists all voices available for use with the service. The information includes the - name, language, gender, and other details about the voice. To see information - about a specific voice, use the **Get a voice** method. + name, language, gender, and other details about the voice. The ordering of the + list of voices can change from call to call; do not rely on an alphabetized or + static list of voices. To see information about a specific voice, use the **Get a + voice** method. **See also:** [Listing all available voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). @@ -888,9 +890,13 @@ def delete_user_data(self, customer_id: str, deletes all data for the customer ID, regardless of the method by which the information was added. The method has no effect if no data is associated with the customer ID. You must issue the request with credentials for the same instance of - the service that was used to associate the customer ID with the data. - You associate a customer ID with data by passing the `X-Watson-Metadata` header - with a request that passes the data. + the service that was used to associate the customer ID with the data. You + associate a customer ID with data by passing the `X-Watson-Metadata` header with a + request that passes the data. + **Note:** If you delete an instance of the service from the service console, all + data associated with that service instance is automatically deleted. This includes + all custom voice models and word/translation pairs, and all data related to speech + synthesis requests. **See also:** [Information security](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-information-security#information-security). @@ -936,6 +942,8 @@ class Voice(Enum): DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' @@ -956,6 +964,7 @@ class Voice(Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' @@ -1006,6 +1015,8 @@ class Voice(Enum): DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' @@ -1026,6 +1037,7 @@ class Voice(Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' @@ -1057,6 +1069,8 @@ class Voice(Enum): DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' @@ -1077,6 +1091,7 @@ class Voice(Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 88ec65e8d..d9fd44f14 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -43,7 +43,7 @@ class ToneAnalyzerV3(BaseService): """The Tone Analyzer V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/tone-analyzer/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'tone_analyzer' def __init__( diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index efef3065a..47e97fafb 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -41,7 +41,7 @@ class VisualRecognitionV3(BaseService): """The Visual Recognition V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index d256258f7..79b32f3fd 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -40,7 +40,7 @@ class VisualRecognitionV4(BaseService): """The Visual Recognition V4 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( From 99555f017a08fa42457fbebdaf4d03a854482683 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:28:59 -0400 Subject: [PATCH 5/7] feat: generate unit tests using current api defs --- test/unit/test_assistant_v1.py | 4 +- test/unit/test_assistant_v2.py | 169 ++- test/unit/test_compare_comply_v1.py | 4 +- test/unit/test_discovery_v1.py | 4 +- test/unit/test_discovery_v2.py | 1114 ++++++++++++++++- test/unit/test_language_translator_v3.py | 82 +- .../test_natural_language_classifier_v1.py | 4 +- .../test_natural_language_understanding_v1.py | 2 +- test/unit/test_personality_insights_v3.py | 4 +- test/unit/test_speech_to_text_v1.py | 4 +- test/unit/test_text_to_speech_v1.py | 4 +- test/unit/test_tone_analyzer_v3.py | 4 +- test/unit/test_visual_recognition_v3.py | 4 +- test/unit/test_visual_recognition_v4.py | 4 +- 14 files changed, 1380 insertions(+), 27 deletions(-) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index bc1ed2ad3..e0db9de56 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import ibm_watson.assistant_v1 from ibm_watson.assistant_v1 import * -base_url = 'https://gateway.watsonplatform.net/assistant/api' +base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' ############################################################################## # Start of Service: Message diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index c9782ee8a..9056aa0ba 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.assistant_v2 from ibm_watson.assistant_v2 import * -base_url = 'https://gateway.watsonplatform.net/assistant/api' +base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' ############################################################################## # Start of Service: Sessions @@ -329,6 +329,170 @@ def construct_required_body(self): # End of Service: Message ############################################################################## +############################################################################## +# Start of Service: Logs +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_logs +#----------------------------------------------------------------------------- +class TestListLogs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_response(self): + body = self.construct_full_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_empty(self): + check_empty_required_params(self, fake_response_LogCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/logs'.format(body['assistant_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2020-04-01', + ) + service.set_service_url(base_url) + output = service.list_logs(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + body['sort'] = "string1" + body['filter'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Logs +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=202, + content_type='') + + def call_service(self, body): + service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2020-04-01', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + def check_empty_required_params(obj, response): """Test function to assert that the operation will throw an error when given empty required data @@ -397,3 +561,4 @@ def send_request(obj, body, response, url=None): fake_response_SessionResponse_json = """{"session_id": "fake_session_id"}""" fake_response_MessageResponse_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" fake_response_MessageResponseStateless_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" +fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 753607be4..b3753aa22 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.compare_comply_v1 from ibm_watson.compare_comply_v1 import * -base_url = 'https://gateway.watsonplatform.net/compare-comply/api' +base_url = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' ############################################################################## # Start of Service: HTMLConversion diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index d18699074..b3294d735 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.discovery_v1 from ibm_watson.discovery_v1 import * -base_url = 'https://gateway.watsonplatform.net/discovery/api' +base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' ############################################################################## # Start of Service: Environments diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index d5f320933..bccc2efcf 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.discovery_v2 from ibm_watson.discovery_v2 import * -base_url = 'https://fake' +base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' ############################################################################## # Start of Service: Collections @@ -100,6 +100,296 @@ def construct_required_body(self): return body +#----------------------------------------------------------------------------- +# Test Class for create_collection +#----------------------------------------------------------------------------- +class TestCreateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_response(self): + body = self.construct_full_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_empty(self): + check_empty_required_params(self, fake_response_CollectionDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections'.format(body['project_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.create_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body.update({"name": "string1", "description": "string1", "language": "string1", "enrichments": [], }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body.update({"name": "string1", "description": "string1", "language": "string1", "enrichments": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_collection +#----------------------------------------------------------------------------- +class TestGetCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_response(self): + body = self.construct_full_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_empty(self): + check_empty_required_params(self, fake_response_CollectionDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.get_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_collection +#----------------------------------------------------------------------------- +class TestUpdateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_response(self): + body = self.construct_full_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_empty(self): + check_empty_required_params(self, fake_response_CollectionDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.update_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "enrichments": [], }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "enrichments": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_collection +#----------------------------------------------------------------------------- +class TestDeleteCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + # endregion ############################################################################## # End of Service: Collections @@ -1096,6 +1386,815 @@ def construct_required_body(self): # End of Service: TrainingData ############################################################################## +############################################################################## +# Start of Service: Enrichments +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_enrichments +#----------------------------------------------------------------------------- +class TestListEnrichments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_enrichments_response(self): + body = self.construct_full_body() + response = fake_response_Enrichments_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_enrichments_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichments_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_enrichments_empty(self): + check_empty_required_params(self, fake_response_Enrichments_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments'.format(body['project_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.list_enrichments(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_enrichment +#----------------------------------------------------------------------------- +class TestCreateEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_enrichment_response(self): + body = self.construct_full_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_enrichment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_enrichment_empty(self): + check_empty_required_params(self, fake_response_Enrichment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments'.format(body['project_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.create_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment'] = {"enrichment": {"mock": "data"}} + body['file'] = tempfile.NamedTemporaryFile() + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment'] = {"enrichment": {"mock": "data"}} + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_enrichment +#----------------------------------------------------------------------------- +class TestGetEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_enrichment_response(self): + body = self.construct_full_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_enrichment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_enrichment_empty(self): + check_empty_required_params(self, fake_response_Enrichment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.get_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_enrichment +#----------------------------------------------------------------------------- +class TestUpdateEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_enrichment_response(self): + body = self.construct_full_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_enrichment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_enrichment_empty(self): + check_empty_required_params(self, fake_response_Enrichment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.update_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + body.update({"name": "string1", "description": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + body.update({"name": "string1", "description": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_enrichment +#----------------------------------------------------------------------------- +class TestDeleteEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_enrichment_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_enrichment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_enrichment_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Enrichments +############################################################################## + +############################################################################## +# Start of Service: Projects +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_projects +#----------------------------------------------------------------------------- +class TestListProjects(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_projects_response(self): + body = self.construct_full_body() + response = fake_response_ListProjectsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_projects_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListProjectsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_projects_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.list_projects(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_project +#----------------------------------------------------------------------------- +class TestCreateProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_project_response(self): + body = self.construct_full_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_project_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_project_empty(self): + check_empty_required_params(self, fake_response_ProjectDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.create_project(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"name": "string1", "type": "string1", "default_query_parameters": DefaultQueryParams._from_dict(json.loads("""{"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}""")), }) + return body + + def construct_required_body(self): + body = dict() + body.update({"name": "string1", "type": "string1", "default_query_parameters": DefaultQueryParams._from_dict(json.loads("""{"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_project +#----------------------------------------------------------------------------- +class TestGetProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_project_response(self): + body = self.construct_full_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_project_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_project_empty(self): + check_empty_required_params(self, fake_response_ProjectDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}'.format(body['project_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.get_project(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_project +#----------------------------------------------------------------------------- +class TestUpdateProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_project_response(self): + body = self.construct_full_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_project_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_project_empty(self): + check_empty_required_params(self, fake_response_ProjectDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}'.format(body['project_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.update_project(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body.update({"name": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_project +#----------------------------------------------------------------------------- +class TestDeleteProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_project_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_project_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_project_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}'.format(body['project_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_project(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Projects +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_empty(self): + check_empty_required_params(self, fake_response__json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + def check_empty_required_params(obj, response): """Test function to assert that the operation will throw an error when given empty required data @@ -1162,6 +2261,9 @@ def send_request(obj, body, response, url=None): fake_response__json = None fake_response_ListCollectionsResponse_json = """{"collections": []}""" +fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" +fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" +fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query", "suggested_refinements": [], "table_results": []}""" fake_response_Completions_json = """{"completions": []}""" fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "notices": []}""" @@ -1174,3 +2276,11 @@ def send_request(obj, body, response, url=None): fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_Enrichments_json = """{"enrichments": []}""" +fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" +fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" +fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" +fake_response_ListProjectsResponse_json = """{"projects": []}""" +fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" +fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" +fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 65586dff3..5d732d7f6 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,84 @@ import ibm_watson.language_translator_v3 from ibm_watson.language_translator_v3 import * -base_url = 'https://gateway.watsonplatform.net/language-translator/api' +base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' + +############################################################################## +# Start of Service: Languages +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_languages +#----------------------------------------------------------------------------- +class TestListLanguages(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_languages_response(self): + body = self.construct_full_body() + response = fake_response_Languages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_languages_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Languages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_languages_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/languages' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_languages(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +# endregion +############################################################################## +# End of Service: Languages +############################################################################## ############################################################################## # Start of Service: Translation @@ -974,6 +1051,7 @@ def send_request(obj, body, response, url=None): #################### fake_response__json = None +fake_response_Languages_json = """{"languages": []}""" fake_response_TranslationResult_json = """{"word_count": 10, "character_count": 15, "detected_language": "fake_detected_language", "detected_language_confidence": 28, "translations": []}""" fake_response_IdentifiableLanguages_json = """{"languages": []}""" fake_response_IdentifiedLanguages_json = """{"languages": []}""" diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 3c142ef6c..3fb8d18ab 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.natural_language_classifier_v1 from ibm_watson.natural_language_classifier_v1 import * -base_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' +base_url = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' ############################################################################## # Start of Service: ClassifyText diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 0857daea3..2def05826 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -22,7 +22,7 @@ import ibm_watson.natural_language_understanding_v1 from ibm_watson.natural_language_understanding_v1 import * -base_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' +base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' ############################################################################## # Start of Service: Analyze diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index fe646402f..dcbc29a2d 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.personality_insights_v3 from ibm_watson.personality_insights_v3 import * -base_url = 'https://gateway.watsonplatform.net/personality-insights/api' +base_url = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' ############################################################################## # Start of Service: Methods diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 8b8aff3e2..415c54fe8 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import ibm_watson.speech_to_text_v1 from ibm_watson.speech_to_text_v1 import * -base_url = 'https://stream.watsonplatform.net/speech-to-text/api' +base_url = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' ############################################################################## # Start of Service: Models diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index b9b89e2a7..57eda15aa 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.text_to_speech_v1 from ibm_watson.text_to_speech_v1 import * -base_url = 'https://stream.watsonplatform.net/text-to-speech/api' +base_url = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' ############################################################################## # Start of Service: Voices diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index f9e5a577e..13a2928e5 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.tone_analyzer_v3 from ibm_watson.tone_analyzer_v3 import * -base_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' +base_url = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' ############################################################################## # Start of Service: Methods diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index a469b83c9..af2790c7a 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.visual_recognition_v3 from ibm_watson.visual_recognition_v3 import * -base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' +base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' ############################################################################## # Start of Service: General diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index ee589767d..a5850db62 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.visual_recognition_v4 from ibm_watson.visual_recognition_v4 import * -base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' +base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' ############################################################################## # Start of Service: Analysis From 7ddb0c3a43cdb9ece492c51ad45d134b52909e87 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:29:39 -0400 Subject: [PATCH 6/7] test: add test doc for create enrichment test --- resources/TestEnrichments.csv | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 resources/TestEnrichments.csv diff --git a/resources/TestEnrichments.csv b/resources/TestEnrichments.csv new file mode 100644 index 000000000..0acd7812b --- /dev/null +++ b/resources/TestEnrichments.csv @@ -0,0 +1,2 @@ +engine,gasket,piston,valves +flag,green,yellow,red \ No newline at end of file From a091f2418df33ebba7017d1d9e59e03b413069c5 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:32:16 -0400 Subject: [PATCH 7/7] chore: fix copyrights --- test/unit/test_assistant_v1.py | 2 +- test/unit/test_assistant_v2.py | 2 +- test/unit/test_compare_comply_v1.py | 2 +- test/unit/test_discovery_v1.py | 2 +- test/unit/test_discovery_v2.py | 2 +- test/unit/test_language_translator_v3.py | 2 +- test/unit/test_natural_language_classifier_v1.py | 2 +- test/unit/test_personality_insights_v3.py | 2 +- test/unit/test_speech_to_text_v1.py | 2 +- test/unit/test_text_to_speech_v1.py | 2 +- test/unit/test_tone_analyzer_v3.py | 2 +- test/unit/test_visual_recognition_v3.py | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index e0db9de56..cff1fdcc1 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 9056aa0ba..a0b8cf62b 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index b3753aa22..577a098a8 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index b3294d735..9d5dff330 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index bccc2efcf..9a36411c9 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 5d732d7f6..105e27faf 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 3fb8d18ab..8485c8f02 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index dcbc29a2d..e36cce0c1 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 415c54fe8..5a9dd4a4a 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 57eda15aa..31b2f739e 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 13a2928e5..12ca4aaa8 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index af2790c7a..1608ba69a 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.