watson-developer-cloud-2.10.1/0000755000076500000240000000000013451440673017650 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/PKG-INFO0000644000076500000240000004536713451440673020764 0ustar erikadsouzastaff00000000000000Metadata-Version: 1.1 Name: watson-developer-cloud Version: 2.10.1 Summary: Client library to use the IBM Watson Services Home-page: https://github.com/watson-developer-cloud/python-sdk Author: Jeffrey Stylos Author-email: jsstylos@us.ibm.com License: Apache 2.0 Description-Content-Type: UNKNOWN Description: Watson Developer Cloud Python SDK ================================= |Build Status| |Slack| |Latest Stable Version| |CLA assistant| Python client library to quickly get started with the various `Watson APIs `__ services. Table of Contents - `Before you begin <#before-you-begin>`__ - `Installation <#installation>`__ - `Examples <#examples>`__ - `Running in IBM Cloud <#running-in-ibm-cloud>`__ - `Authentication <#authentication>`__ - `Getting credentials <#getting-credentials>`__ - `IAM <#iam>`__ - `Username and password <#username-and-password>`__ - `Python version <#python-version>`__ - `Changes for v1.0 <#changes-for-v10>`__ - `Changes for v2.0 <#changes-for-v20>`__ - `Migration <#migration>`__ - `Configuring the http client <#configuring-the-http-client-supported-from-v110>`__ - `Disable SSL certificate verification <#disable-ssl-certificate-verification>`__ - `Sending request headers <#sending-request-headers>`__ - `Parsing HTTP response info <#parsing-http-response-info>`__ - `Dependencies <#dependencies>`__ - `License <#license>`__ - `Contributing <#contributing>`__ Before you begin ---------------- - You need an `IBM Cloud `__ account. Installation ------------ Note: We are moving to ``ibm-watson``. All versions prior to v3.0.0 can still be found in ``watson-developer-cloud`` To install, use ``pip`` or ``easy_install``: .. code:: bash pip install --upgrade watson-developer-cloud or .. code:: bash easy_install --upgrade watson-developer-cloud Note the following: a) If you run into permission issues try: .. code:: bash sudo -H pip install --ignore-installed six watson-developer-cloud For more details see `#225 `__ b) In case you run into problems installing the SDK in DSX, try :: !pip install --upgrade pip Restarting the kernel For more details see `#405 `__ Examples -------- The `examples `__ folder has basic and advanced examples. The examples within each service assume that you already have `service credentials <#getting-credentials>`__. Running in IBM Cloud -------------------- If you run your app in IBM Cloud, the SDK gets credentials from the ```VCAP_SERVICES`` `__ environment variable. Authentication -------------- Watson services are migrating to token-based Identity and Access Management (IAM) authentication. - With some service instances, you authenticate to the API by using **`IAM <#iam>`__**. - In other instances, you authenticate by providing the **`username and password <#username-and-password>`__** for the service instance. **Note:** Authenticating with the X-Watson-Authorization-Token header is deprecated. The token continues to work with Cloud Foundry services, but is not supported for services that use Identity and Access Management (IAM) authentication. See `here <#iam>`__ for details. Getting credentials ~~~~~~~~~~~~~~~~~~~ To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services: 1. Go to the IBM Cloud `Dashboard `__ page. 2. Either click an existing Watson service instance in your `resource list `__ or click `**Create resource > AI** `__ and create a service instance. 3. Click on the **Manage** item in the left nav bar of your service instance. On this page, you should be able to see your credentials for accessing your service instance. Supplying credentials ~~~~~~~~~~~~~~~~~~~~~ There are two ways to supply the credentials you found above to the SDK for authentication. Credential file (easier!) ^^^^^^^^^^^^^^^^^^^^^^^^^ With a credential file, you just need to put the file in the right place and the SDK will do the work of parsing and authenticating. You can get this file by clicking the **Download** button for the credentials in the **Manage** tab of your service instance. The file downloaded will be called ``ibm-credentials.env``. This is the name the SDK will search for and **must** be preserved unless you want to configure the file path (more on that later). The SDK will look for your ``ibm-credentials.env`` file in the following places (in order): - Your system's home directory - The top-level directory of the project you're using the SDK in As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: .. code:: python discovery = DiscoveryV1(version='2018-08-01') And that's it! If you're using more than one service at a time in your code and get two different ``ibm-credentials.env`` files, just put the contents together in one ``ibm-credentials.env`` file and the SDK will handle assigning credentials to their appropriate services. If you would like to configure the location/name of your credential file, you can set an environment variable called ``IBM_CREDENTIALS_FILE``. **This will take precedence over the locations specified above.** Here's how you can do that: .. code:: bash export IBM_CREDENTIALS_FILE="" where ```` is something like ``/home/user/Downloads/.env``. Manually ^^^^^^^^ If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you. IAM ~~~ IBM Cloud is migrating to token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated. You supply either an IAM service **API key** or an **access token**: - Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary. - Use the access token if you want to manage the lifecycle yourself. For details, see `Authenticating with IAM tokens `__. Supplying the IAM API key ^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python # In the constructor, letting the SDK manage the IAM token discovery = DiscoveryV1(version='2018-08-01', url='', iam_apikey='', iam_url='') # optional - the default value is https://iam.bluemix.net/identity/token .. code:: python # after instantiation, letting the SDK manage the IAM token discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_iam_apikey('') Supplying the access token ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python # in the constructor, assuming control of managing IAM token discovery = DiscoveryV1(version='2018-08-01', url='', iam_access_token='') .. code:: python # after instantiation, assuming control of managing IAM token discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_iam_access_token('') Username and password ~~~~~~~~~~~~~~~~~~~~~ .. code:: python from watson_developer_cloud import DiscoveryV1 # In the constructor discovery = DiscoveryV1(version='2018-08-01', url='', username='', password='') .. code:: python # After instantiation discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_username_and_password('', '') Python version -------------- Tested on Python 2.7, 3.4, 3.5, and 3.6. Changes for v1.0 ---------------- Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the `changelog `__ for the details. Changes for v2.0 ---------------- ``DetailedResponse`` which contains the result, headers and HTTP status code is now the default response for all methods. .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}) print(response.get_result()) print(response.get_headers()) print(response.get_status_code()) See the `changelog `__ for the details. Migration --------- This version includes many breaking changes as a result of standardizing behavior across the new generated services. Full details on migration from previous versions can be found `here `__. Configuring the http client (Supported from v1.1.0) --------------------------------------------------- To set client configs like timeout use the ``with_http_config()`` function and pass it a dictionary of configs. .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') assistant.set_http_config({'timeout': 100}) response = assistant.message(workspace_id=workspace_id, input={ 'text': 'What\'s the weather like?'}).get_result() print(json.dumps(response, indent=2)) Disable SSL certificate verification ------------------------------------ For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: .. code:: python service.disable_SSL_verification() Sending request headers ----------------------- Custom headers can be passed in any request in the form of a ``dict`` as: .. code:: python headers = { 'Custom-Header': 'custom_value' } For example, to send a header called ``Custom-Header`` to a call in Watson Assistant, pass the headers parameter as: .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() Parsing HTTP response info -------------------------- If you would like access to some HTTP response information along with the response model, you can set the ``set_detailed_response()`` to ``True``. Since Python SDK ``v2.0``, it is set to ``True`` .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() print(response) This would give an output of ``DetailedResponse`` having the structure: .. code:: python { 'result': , 'headers': { }, 'status_code': } You can use the ``get_result()``, ``get_headers()`` and get\_status\_code() to return the result, headers and status code respectively. Using Websockets ---------------- The Text to Speech service supports synthesizing text to spoken audio using web sockets with the ``synthesize_using_websocket``. The Speech to Text service supports recognizing speech to text using web sockets with the ``recognize_using_websocket``. These methods need a custom callback class to listen to events. Below is an example of ``synthesize_using_websocket``. Note: The service accepts one request per connection. .. code:: py from watson_developer_cloud.websocket import SynthesizeCallback class MySynthesizeCallback(SynthesizeCallback): def __init__(self): SynthesizeCallback.__init__(self) def on_audio_stream(self, audio_stream): return audio_stream def on_data(self, data): return data my_callback = MySynthesizeCallback() service.synthesize_using_websocket('I like to pet dogs', my_callback, accept='audio/wav', voice='en-US_AllisonVoice' ) Dependencies ------------ - `requests `__ - ``python_dateutil`` >= 2.5.3 - `responses `__ for testing - Following for web sockets support in speech to text - ``websocket-client`` 0.48.0 Contributing ------------ See `CONTRIBUTING.md `__. License ------- This library is licensed under the `Apache 2.0 license `__. .. |Build Status| image:: https://travis-ci.org/watson-developer-cloud/python-sdk.svg?branch=master :target: https://travis-ci.org/watson-developer-cloud/python-sdk .. |Slack| image:: https://wdc-slack-inviter.mybluemix.net/badge.svg :target: https://wdc-slack-inviter.mybluemix.net .. |Latest Stable Version| image:: https://img.shields.io/pypi/v/watson-developer-cloud.svg :target: https://pypi.python.org/pypi/watson-developer-cloud .. |CLA assistant| image:: https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk :target: https://cla-assistant.io/watson-developer-cloud/python-sdk Keywords: language,vision,question and answer tone_analyzer,natural language classifier,text to speech,language translation,language identification,concept expansion,machine translation,personality insights,message resonance,watson developer cloud,wdc,watson,ibm,dialog,user modeling,tone analyzer,speech to text,visual recognition Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Software Development :: Libraries :: Application Frameworks watson-developer-cloud-2.10.1/LICENSE0000644000076500000240000002367613173433060020664 0ustar erikadsouzastaff00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS watson-developer-cloud-2.10.1/MANIFEST.in0000644000076500000240000000025113451407070021376 0ustar erikadsouzastaff00000000000000include README.md include LICENSE recursive-include examples *.py *.md recursive-include watson_developer_cloud *.py *.md global-exclude .DS_Store global-exclude *.pyc watson-developer-cloud-2.10.1/watson_developer_cloud.egg-info/0000755000076500000240000000000013451440673026110 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud.egg-info/PKG-INFO0000644000076500000240000004536713451440673027224 0ustar erikadsouzastaff00000000000000Metadata-Version: 1.1 Name: watson-developer-cloud Version: 2.10.1 Summary: Client library to use the IBM Watson Services Home-page: https://github.com/watson-developer-cloud/python-sdk Author: Jeffrey Stylos Author-email: jsstylos@us.ibm.com License: Apache 2.0 Description-Content-Type: UNKNOWN Description: Watson Developer Cloud Python SDK ================================= |Build Status| |Slack| |Latest Stable Version| |CLA assistant| Python client library to quickly get started with the various `Watson APIs `__ services. Table of Contents - `Before you begin <#before-you-begin>`__ - `Installation <#installation>`__ - `Examples <#examples>`__ - `Running in IBM Cloud <#running-in-ibm-cloud>`__ - `Authentication <#authentication>`__ - `Getting credentials <#getting-credentials>`__ - `IAM <#iam>`__ - `Username and password <#username-and-password>`__ - `Python version <#python-version>`__ - `Changes for v1.0 <#changes-for-v10>`__ - `Changes for v2.0 <#changes-for-v20>`__ - `Migration <#migration>`__ - `Configuring the http client <#configuring-the-http-client-supported-from-v110>`__ - `Disable SSL certificate verification <#disable-ssl-certificate-verification>`__ - `Sending request headers <#sending-request-headers>`__ - `Parsing HTTP response info <#parsing-http-response-info>`__ - `Dependencies <#dependencies>`__ - `License <#license>`__ - `Contributing <#contributing>`__ Before you begin ---------------- - You need an `IBM Cloud `__ account. Installation ------------ Note: We are moving to ``ibm-watson``. All versions prior to v3.0.0 can still be found in ``watson-developer-cloud`` To install, use ``pip`` or ``easy_install``: .. code:: bash pip install --upgrade watson-developer-cloud or .. code:: bash easy_install --upgrade watson-developer-cloud Note the following: a) If you run into permission issues try: .. code:: bash sudo -H pip install --ignore-installed six watson-developer-cloud For more details see `#225 `__ b) In case you run into problems installing the SDK in DSX, try :: !pip install --upgrade pip Restarting the kernel For more details see `#405 `__ Examples -------- The `examples `__ folder has basic and advanced examples. The examples within each service assume that you already have `service credentials <#getting-credentials>`__. Running in IBM Cloud -------------------- If you run your app in IBM Cloud, the SDK gets credentials from the ```VCAP_SERVICES`` `__ environment variable. Authentication -------------- Watson services are migrating to token-based Identity and Access Management (IAM) authentication. - With some service instances, you authenticate to the API by using **`IAM <#iam>`__**. - In other instances, you authenticate by providing the **`username and password <#username-and-password>`__** for the service instance. **Note:** Authenticating with the X-Watson-Authorization-Token header is deprecated. The token continues to work with Cloud Foundry services, but is not supported for services that use Identity and Access Management (IAM) authentication. See `here <#iam>`__ for details. Getting credentials ~~~~~~~~~~~~~~~~~~~ To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services: 1. Go to the IBM Cloud `Dashboard `__ page. 2. Either click an existing Watson service instance in your `resource list `__ or click `**Create resource > AI** `__ and create a service instance. 3. Click on the **Manage** item in the left nav bar of your service instance. On this page, you should be able to see your credentials for accessing your service instance. Supplying credentials ~~~~~~~~~~~~~~~~~~~~~ There are two ways to supply the credentials you found above to the SDK for authentication. Credential file (easier!) ^^^^^^^^^^^^^^^^^^^^^^^^^ With a credential file, you just need to put the file in the right place and the SDK will do the work of parsing and authenticating. You can get this file by clicking the **Download** button for the credentials in the **Manage** tab of your service instance. The file downloaded will be called ``ibm-credentials.env``. This is the name the SDK will search for and **must** be preserved unless you want to configure the file path (more on that later). The SDK will look for your ``ibm-credentials.env`` file in the following places (in order): - Your system's home directory - The top-level directory of the project you're using the SDK in As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: .. code:: python discovery = DiscoveryV1(version='2018-08-01') And that's it! If you're using more than one service at a time in your code and get two different ``ibm-credentials.env`` files, just put the contents together in one ``ibm-credentials.env`` file and the SDK will handle assigning credentials to their appropriate services. If you would like to configure the location/name of your credential file, you can set an environment variable called ``IBM_CREDENTIALS_FILE``. **This will take precedence over the locations specified above.** Here's how you can do that: .. code:: bash export IBM_CREDENTIALS_FILE="" where ```` is something like ``/home/user/Downloads/.env``. Manually ^^^^^^^^ If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you. IAM ~~~ IBM Cloud is migrating to token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated. You supply either an IAM service **API key** or an **access token**: - Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary. - Use the access token if you want to manage the lifecycle yourself. For details, see `Authenticating with IAM tokens `__. Supplying the IAM API key ^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python # In the constructor, letting the SDK manage the IAM token discovery = DiscoveryV1(version='2018-08-01', url='', iam_apikey='', iam_url='') # optional - the default value is https://iam.bluemix.net/identity/token .. code:: python # after instantiation, letting the SDK manage the IAM token discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_iam_apikey('') Supplying the access token ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python # in the constructor, assuming control of managing IAM token discovery = DiscoveryV1(version='2018-08-01', url='', iam_access_token='') .. code:: python # after instantiation, assuming control of managing IAM token discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_iam_access_token('') Username and password ~~~~~~~~~~~~~~~~~~~~~ .. code:: python from watson_developer_cloud import DiscoveryV1 # In the constructor discovery = DiscoveryV1(version='2018-08-01', url='', username='', password='') .. code:: python # After instantiation discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_username_and_password('', '') Python version -------------- Tested on Python 2.7, 3.4, 3.5, and 3.6. Changes for v1.0 ---------------- Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the `changelog `__ for the details. Changes for v2.0 ---------------- ``DetailedResponse`` which contains the result, headers and HTTP status code is now the default response for all methods. .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}) print(response.get_result()) print(response.get_headers()) print(response.get_status_code()) See the `changelog `__ for the details. Migration --------- This version includes many breaking changes as a result of standardizing behavior across the new generated services. Full details on migration from previous versions can be found `here `__. Configuring the http client (Supported from v1.1.0) --------------------------------------------------- To set client configs like timeout use the ``with_http_config()`` function and pass it a dictionary of configs. .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') assistant.set_http_config({'timeout': 100}) response = assistant.message(workspace_id=workspace_id, input={ 'text': 'What\'s the weather like?'}).get_result() print(json.dumps(response, indent=2)) Disable SSL certificate verification ------------------------------------ For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: .. code:: python service.disable_SSL_verification() Sending request headers ----------------------- Custom headers can be passed in any request in the form of a ``dict`` as: .. code:: python headers = { 'Custom-Header': 'custom_value' } For example, to send a header called ``Custom-Header`` to a call in Watson Assistant, pass the headers parameter as: .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() Parsing HTTP response info -------------------------- If you would like access to some HTTP response information along with the response model, you can set the ``set_detailed_response()`` to ``True``. Since Python SDK ``v2.0``, it is set to ``True`` .. code:: python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() print(response) This would give an output of ``DetailedResponse`` having the structure: .. code:: python { 'result': , 'headers': { }, 'status_code': } You can use the ``get_result()``, ``get_headers()`` and get\_status\_code() to return the result, headers and status code respectively. Using Websockets ---------------- The Text to Speech service supports synthesizing text to spoken audio using web sockets with the ``synthesize_using_websocket``. The Speech to Text service supports recognizing speech to text using web sockets with the ``recognize_using_websocket``. These methods need a custom callback class to listen to events. Below is an example of ``synthesize_using_websocket``. Note: The service accepts one request per connection. .. code:: py from watson_developer_cloud.websocket import SynthesizeCallback class MySynthesizeCallback(SynthesizeCallback): def __init__(self): SynthesizeCallback.__init__(self) def on_audio_stream(self, audio_stream): return audio_stream def on_data(self, data): return data my_callback = MySynthesizeCallback() service.synthesize_using_websocket('I like to pet dogs', my_callback, accept='audio/wav', voice='en-US_AllisonVoice' ) Dependencies ------------ - `requests `__ - ``python_dateutil`` >= 2.5.3 - `responses `__ for testing - Following for web sockets support in speech to text - ``websocket-client`` 0.48.0 Contributing ------------ See `CONTRIBUTING.md `__. License ------- This library is licensed under the `Apache 2.0 license `__. .. |Build Status| image:: https://travis-ci.org/watson-developer-cloud/python-sdk.svg?branch=master :target: https://travis-ci.org/watson-developer-cloud/python-sdk .. |Slack| image:: https://wdc-slack-inviter.mybluemix.net/badge.svg :target: https://wdc-slack-inviter.mybluemix.net .. |Latest Stable Version| image:: https://img.shields.io/pypi/v/watson-developer-cloud.svg :target: https://pypi.python.org/pypi/watson-developer-cloud .. |CLA assistant| image:: https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk :target: https://cla-assistant.io/watson-developer-cloud/python-sdk Keywords: language,vision,question and answer tone_analyzer,natural language classifier,text to speech,language translation,language identification,concept expansion,machine translation,personality insights,message resonance,watson developer cloud,wdc,watson,ibm,dialog,user modeling,tone analyzer,speech to text,visual recognition Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Software Development :: Libraries :: Application Frameworks watson-developer-cloud-2.10.1/watson_developer_cloud.egg-info/zip-safe0000644000076500000240000000000113450444255027537 0ustar erikadsouzastaff00000000000000 watson-developer-cloud-2.10.1/watson_developer_cloud.egg-info/SOURCES.txt0000644000076500000240000000471513451440673030003 0ustar erikadsouzastaff00000000000000LICENSE MANIFEST.in README.md setup.py examples/README.md examples/__init__.py examples/assistant_v1.py examples/assistant_v2.py examples/authorization_v1.py examples/discovery_v1.py examples/language_translator_v3.py examples/microphone-speech-to-text.py examples/natural_language_classifier_v1.py examples/natural_language_understanding_v1.py examples/personality_insights_v3.py examples/speaker_text_to_speech.py examples/speech_to_text_v1.py examples/text_to_speech_v1.py examples/tone_analyzer_v3.py examples/visual_recognition_v3.py examples/conversation_tone_analyzer_integration/README.md examples/conversation_tone_analyzer_integration/__init__.py examples/conversation_tone_analyzer_integration/tone_conversation_integration.v1.py examples/conversation_tone_analyzer_integration/tone_detection.py watson_developer_cloud/__init__.py watson_developer_cloud/assistant_v1.py watson_developer_cloud/assistant_v2.py watson_developer_cloud/authorization_v1.py watson_developer_cloud/compare_comply_v1.py watson_developer_cloud/discovery_v1.py watson_developer_cloud/iam_token_manager.py watson_developer_cloud/language_translator_v3.py watson_developer_cloud/natural_language_classifier_v1.py watson_developer_cloud/natural_language_understanding_v1.py watson_developer_cloud/personality_insights_v3.py watson_developer_cloud/speech_to_text_v1.py watson_developer_cloud/speech_to_text_v1_adapter.py watson_developer_cloud/text_to_speech_adapter_v1.py watson_developer_cloud/text_to_speech_v1.py watson_developer_cloud/tone_analyzer_v3.py watson_developer_cloud/utils.py watson_developer_cloud/version.py watson_developer_cloud/visual_recognition_v3.py watson_developer_cloud/watson_service.py watson_developer_cloud.egg-info/PKG-INFO watson_developer_cloud.egg-info/SOURCES.txt watson_developer_cloud.egg-info/dependency_links.txt watson_developer_cloud.egg-info/requires.txt watson_developer_cloud.egg-info/top_level.txt watson_developer_cloud.egg-info/zip-safe watson_developer_cloud/natural_language_understanding/__init__.py watson_developer_cloud/natural_language_understanding/features/__init__.py watson_developer_cloud/natural_language_understanding/features/v1/__init__.py watson_developer_cloud/websocket/__init__.py watson_developer_cloud/websocket/audio_source.py watson_developer_cloud/websocket/recognize_abstract_callback.py watson_developer_cloud/websocket/recognize_listener.py watson_developer_cloud/websocket/synthesize_callback.py watson_developer_cloud/websocket/synthesize_listener.pywatson-developer-cloud-2.10.1/watson_developer_cloud.egg-info/requires.txt0000644000076500000240000000010313451440673030502 0ustar erikadsouzastaff00000000000000requests<3.0,>=2.0 python_dateutil>=2.5.3 websocket-client==0.48.0 watson-developer-cloud-2.10.1/watson_developer_cloud.egg-info/top_level.txt0000644000076500000240000000002713451440673030641 0ustar erikadsouzastaff00000000000000watson_developer_cloud watson-developer-cloud-2.10.1/watson_developer_cloud.egg-info/dependency_links.txt0000644000076500000240000000000113451440673032156 0ustar erikadsouzastaff00000000000000 watson-developer-cloud-2.10.1/README.md0000755000076500000240000003233513451407070021132 0ustar erikadsouzastaff00000000000000# Watson Developer Cloud Python SDK [![Build Status](https://travis-ci.org/watson-developer-cloud/python-sdk.svg?branch=master)](https://travis-ci.org/watson-developer-cloud/python-sdk) [![Slack](https://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net) [![Latest Stable Version](https://img.shields.io/pypi/v/watson-developer-cloud.svg)](https://pypi.python.org/pypi/watson-developer-cloud) [![CLA assistant](https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk)](https://cla-assistant.io/watson-developer-cloud/python-sdk) Python client library to quickly get started with the various [Watson APIs][wdc] services.
Table of Contents * [Before you begin](#before-you-begin) * [Installation](#installation) * [Examples](#examples) * [Running in IBM Cloud](#running-in-ibm-cloud) * [Authentication](#authentication) * [Getting credentials](#getting-credentials) * [IAM](#iam) * [Username and password](#username-and-password) * [Python version](#python-version) * [Changes for v1.0](#changes-for-v10) * [Changes for v2.0](#changes-for-v20) * [Migration](#migration) * [Configuring the http client](#configuring-the-http-client-supported-from-v110) * [Disable SSL certificate verification](#disable-ssl-certificate-verification) * [Sending request headers](#sending-request-headers) * [Parsing HTTP response info](#parsing-http-response-info) * [Dependencies](#dependencies) * [License](#license) * [Contributing](#contributing)
## Before you begin * You need an [IBM Cloud][ibm-cloud-onboarding] account. ## Installation Note: We are moving to `ibm-watson`. All versions prior to v3.0.0 can still be found in `watson-developer-cloud` To install, use `pip` or `easy_install`: ```bash pip install --upgrade watson-developer-cloud ``` or ```bash easy_install --upgrade watson-developer-cloud ``` Note the following: a) If you run into permission issues try: ```bash sudo -H pip install --ignore-installed six watson-developer-cloud ``` For more details see [#225](https://github.com/watson-developer-cloud/python-sdk/issues/225) b) In case you run into problems installing the SDK in DSX, try ``` !pip install --upgrade pip ``` Restarting the kernel For more details see [#405](https://github.com/watson-developer-cloud/python-sdk/issues/405) ## Examples The [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already have [service credentials](#getting-credentials). ## Running in IBM Cloud If you run your app in IBM Cloud, the SDK gets credentials from the [`VCAP_SERVICES`][vcap_services] environment variable. ## Authentication Watson services are migrating to token-based Identity and Access Management (IAM) authentication. - With some service instances, you authenticate to the API by using **[IAM](#iam)**. - In other instances, you authenticate by providing the **[username and password](#username-and-password)** for the service instance. **Note:** Authenticating with the X-Watson-Authorization-Token header is deprecated. The token continues to work with Cloud Foundry services, but is not supported for services that use Identity and Access Management (IAM) authentication. See [here](#iam) for details. ### Getting credentials To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services: 1. Go to the IBM Cloud [Dashboard](https://cloud.ibm.com/) page. 1. Either click an existing Watson service instance in your [resource list](https://cloud.ibm.com/resources) or click [**Create resource > AI**](https://cloud.ibm.com/catalog?category=ai) and create a service instance. 1. Click on the **Manage** item in the left nav bar of your service instance. On this page, you should be able to see your credentials for accessing your service instance. ### Supplying credentials There are two ways to supply the credentials you found above to the SDK for authentication. #### Credential file (easier!) With a credential file, you just need to put the file in the right place and the SDK will do the work of parsing and authenticating. You can get this file by clicking the **Download** button for the credentials in the **Manage** tab of your service instance. The file downloaded will be called `ibm-credentials.env`. This is the name the SDK will search for and **must** be preserved unless you want to configure the file path (more on that later). The SDK will look for your `ibm-credentials.env` file in the following places (in order): - Your system's home directory - The top-level directory of the project you're using the SDK in As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: ```python discovery = DiscoveryV1(version='2018-08-01') ``` And that's it! If you're using more than one service at a time in your code and get two different `ibm-credentials.env` files, just put the contents together in one `ibm-credentials.env` file and the SDK will handle assigning credentials to their appropriate services. If you would like to configure the location/name of your credential file, you can set an environment variable called `IBM_CREDENTIALS_FILE`. **This will take precedence over the locations specified above.** Here's how you can do that: ```bash export IBM_CREDENTIALS_FILE="" ``` where `` is something like `/home/user/Downloads/.env`. #### Manually If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you. ### IAM IBM Cloud is migrating to token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated. You supply either an IAM service **API key** or an **access token**: - Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary. - Use the access token if you want to manage the lifecycle yourself. For details, see [Authenticating with IAM tokens](https://console.bluemix.net/docs/services/watson/getting-started-iam.html). #### Supplying the IAM API key ```python # In the constructor, letting the SDK manage the IAM token discovery = DiscoveryV1(version='2018-08-01', url='', iam_apikey='', iam_url='') # optional - the default value is https://iam.bluemix.net/identity/token ``` ```python # after instantiation, letting the SDK manage the IAM token discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_iam_apikey('') ``` #### Supplying the access token ```python # in the constructor, assuming control of managing IAM token discovery = DiscoveryV1(version='2018-08-01', url='', iam_access_token='') ``` ```python # after instantiation, assuming control of managing IAM token discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_iam_access_token('') ``` ### Username and password ```python from watson_developer_cloud import DiscoveryV1 # In the constructor discovery = DiscoveryV1(version='2018-08-01', url='', username='', password='') ``` ```python # After instantiation discovery = DiscoveryV1(version='2018-08-01', url='') discovery.set_username_and_password('', '') ``` ## Python version Tested on Python 2.7, 3.4, 3.5, and 3.6. ## Changes for v1.0 Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. ## Changes for v2.0 `DetailedResponse` which contains the result, headers and HTTP status code is now the default response for all methods. ```python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}) print(response.get_result()) print(response.get_headers()) print(response.get_status_code()) ``` See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. ## Migration This version includes many breaking changes as a result of standardizing behavior across the new generated services. Full details on migration from previous versions can be found [here](https://github.com/watson-developer-cloud/python-sdk/wiki/Migration). ## Configuring the http client (Supported from v1.1.0) To set client configs like timeout use the `with_http_config()` function and pass it a dictionary of configs. ```python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') assistant.set_http_config({'timeout': 100}) response = assistant.message(workspace_id=workspace_id, input={ 'text': 'What\'s the weather like?'}).get_result() print(json.dumps(response, indent=2)) ``` ## Disable SSL certificate verification For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: ```python service.disable_SSL_verification() ``` ## Sending request headers Custom headers can be passed in any request in the form of a `dict` as: ```python headers = { 'Custom-Header': 'custom_value' } ``` For example, to send a header called `Custom-Header` to a call in Watson Assistant, pass the headers parameter as: ```python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() ``` ## Parsing HTTP response info If you would like access to some HTTP response information along with the response model, you can set the `set_detailed_response()` to `True`. Since Python SDK `v2.0`, it is set to `True` ```python from watson_developer_cloud import AssistantV1 assistant = AssistantV1( username='xxx', password='yyy', url='', version='2018-07-10') assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() print(response) ``` This would give an output of `DetailedResponse` having the structure: ```python { 'result': , 'headers': { }, 'status_code': } ``` You can use the `get_result()`, `get_headers()` and get_status_code() to return the result, headers and status code respectively. ## Using Websockets The Text to Speech service supports synthesizing text to spoken audio using web sockets with the `synthesize_using_websocket`. The Speech to Text service supports recognizing speech to text using web sockets with the `recognize_using_websocket`. These methods need a custom callback class to listen to events. Below is an example of `synthesize_using_websocket`. Note: The service accepts one request per connection. ```py from watson_developer_cloud.websocket import SynthesizeCallback class MySynthesizeCallback(SynthesizeCallback): def __init__(self): SynthesizeCallback.__init__(self) def on_audio_stream(self, audio_stream): return audio_stream def on_data(self, data): return data my_callback = MySynthesizeCallback() service.synthesize_using_websocket('I like to pet dogs', my_callback, accept='audio/wav', voice='en-US_AllisonVoice' ) ``` ## Dependencies * [requests] * `python_dateutil` >= 2.5.3 * [responses] for testing * Following for web sockets support in speech to text * `websocket-client` 0.48.0 ## Contributing See [CONTRIBUTING.md][CONTRIBUTING]. ## License This library is licensed under the [Apache 2.0 license][license]. [wdc]: http://www.ibm.com/watson/developercloud/ [ibm_cloud]: https://console.bluemix.net [watson-dashboard]: https://console.bluemix.net/dashboard/apps?category=watson [responses]: https://github.com/getsentry/responses [requests]: http://docs.python-requests.org/en/latest/ [examples]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples [CONTRIBUTING]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md [license]: http://www.apache.org/licenses/LICENSE-2.0 [vcap_services]: https://console.bluemix.net/docs/services/watson/getting-started-variables.html [ibm-cloud-onboarding]: http://console.bluemix.net/registration?target=/developer/watson&cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Python watson-developer-cloud-2.10.1/setup.py0000644000076500000240000000665713451437703021400 0ustar erikadsouzastaff00000000000000#!/usr/bin/env python # Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from setuptools import setup from setuptools.command.test import test as TestCommand import os import sys __version__ = '2.10.1' if sys.argv[-1] == 'publish': # test server os.system('python setup.py register -r pypitest') os.system('python setup.py sdist upload -r pypitest') # production server os.system('python setup.py register -r pypi') os.system('python setup.py sdist upload -r pypi') sys.exit() # Convert README.md to README.rst for pypi try: from pypandoc import convert_file def read_md(f): return convert_file(f, 'rst') # read_md = lambda f: convert(f, 'rst') except: print('warning: pypandoc module not found, ' 'could not convert Markdown to RST') def read_md(f): return open(f, 'rb').read().decode(encoding='utf-8') # read_md = lambda f: open(f, 'rb').read().decode(encoding='utf-8') class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['--strict', '--verbose', '--tb=long', 'test'] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(self.test_args) sys.exit(errcode) setup(name='watson-developer-cloud', version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='Jeffrey Stylos', author_email='jsstylos@us.ibm.com', long_description=read_md('README.md'), url='https://github.com/watson-developer-cloud/python-sdk', packages=['watson_developer_cloud'], include_package_data=True, keywords='language, vision, question and answer' + ' tone_analyzer, natural language classifier,' + ' text to speech, language translation, ' + 'language identification, concept expansion, machine translation, ' + 'personality insights, message resonance, watson developer cloud, ' + ' wdc, watson, ibm, dialog, user modeling,' + 'tone analyzer, speech to text, visual recognition', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Libraries :: Application ' 'Frameworks', ], zip_safe=True ) watson-developer-cloud-2.10.1/watson_developer_cloud/0000755000076500000240000000000013451440673024416 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/websocket/0000755000076500000240000000000013451440673026404 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/websocket/synthesize_listener.py0000644000076500000240000000767213451407070033076 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import websocket import json import ssl import time try: import thread except ImportError: import _thread as thread TEN_MILLISECONDS = 0.01 class SynthesizeListener(object): def __init__(self, options, callback, url, headers, http_proxy_host=None, http_proxy_port=None, verify=None): self.options = options self.callback = callback self.url = url self.headers = headers self.http_proxy_host = http_proxy_host self.http_proxy_port = http_proxy_port self.verify = verify # websocket.enableTrace(True) self.ws_client = websocket.WebSocketApp( self.url, header=self.headers, on_open=self.on_open, on_data=self.on_data, on_error=self.on_error, on_close=self.on_close, ) self.ws_client.run_forever(http_proxy_host=self.http_proxy_host, http_proxy_port=self.http_proxy_port, sslopt={'cert_reqs': ssl.CERT_NONE} if self.verify is not None else None) def send_text(self): """ Sends the text message Note: The service handles one request per connection """ def run(*args): """Background process to send the text""" self.ws_client.send(json.dumps(self.options).encode('utf8')) time.sleep(TEN_MILLISECONDS) thread.start_new_thread(run, ()) def on_open(self, ws): """ Callback executed when a connection is opened to the server. Handles sending text to server :param ws: Websocket client """ self.callback.on_connected() self.send_text() def on_data(self, ws, message, message_type, fin): """ Callback executed when message is received from the server. :param ws: Websocket client :param message: utf-8 string which we get from the server. :param message_type: Message type which is either ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY :param fin: continue flag. If 0, the data continues. """ try: if message_type == websocket.ABNF.OPCODE_TEXT: json_object = json.loads(message) if 'binary_streams' in json_object: self.callback.on_content_type(json_object['binary_streams'][0]['content_type']) elif 'error' in json_object: self.on_error(ws, json_object.get('error')) return else: self.callback.on_timing_information(json_object) except Exception: self.on_error(ws, 'Unable to parse received message.') if message_type == websocket.ABNF.OPCODE_BINARY: self.callback.on_audio_stream(message) self.callback.on_data(message) def on_error(self, ws, error): """ Callback executed when an error is received :param ws: Websocket client :param error: Exception object """ self.callback.on_error(error) def on_close(self, ws, **kwargs): """ Callback executed when websocket connection is closed :param ws: Websocket client """ self.callback.on_close() watson-developer-cloud-2.10.1/watson_developer_cloud/websocket/__init__.py0000644000076500000240000000153213451407070030510 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .recognize_abstract_callback import RecognizeCallback from .recognize_listener import RecognizeListener from .audio_source import AudioSource from .synthesize_callback import SynthesizeCallback from .synthesize_listener import SynthesizeListener watson-developer-cloud-2.10.1/watson_developer_cloud/websocket/recognize_listener.py0000644000076500000240000001654413451407070032654 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import websocket import json import time import ssl try: import thread except ImportError: import _thread as thread ONE_KB = 1024 TIMEOUT_PREFIX = "No speech detected for" TEN_MILLISECONDS = 0.01 STATE = "state" ACTION = "action" START = "start" STOP = "stop" class RecognizeListener(object): def __init__(self, audio_source, options, callback, url, headers, http_proxy_host=None, http_proxy_port=None, verify=None): self.audio_source = audio_source self.options = options self.callback = callback self.url = url self.headers = headers self.http_proxy_host = http_proxy_host self.http_proxy_port = http_proxy_port self.isListening = False self.verify = verify # websocket.enableTrace(True) self.ws_client = websocket.WebSocketApp( self.url, header=self.headers, on_open=self.on_open, on_data=self.on_data, on_error=self.on_error, on_close=self.on_close, ) self.ws_client.run_forever(http_proxy_host=self.http_proxy_host, http_proxy_port=self.http_proxy_port, sslopt={"cert_reqs": ssl.CERT_NONE} if self.verify is not None else None) @classmethod def build_start_message(cls, options): options[ACTION] = START return options @classmethod def build_closing_message(cls): return json.dumps({ACTION: STOP}).encode('utf8') @classmethod def extract_transcripts(cls, alternatives): transcripts = [] for alternative in alternatives: transcript = {} if 'confidence' in alternative: transcript['confidence'] = alternative['confidence'] transcript['transcript'] = alternative['transcript'] transcripts.append(transcript) return transcripts def send(self, data, opcode=websocket.ABNF.OPCODE_TEXT): """ Send message to server. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT. """ self.ws_client.send(data, opcode) def send_audio(self, ws): """ Stream audio to server :param ws: Websocket client """ def run(*args): """Background process to stream the data""" if not self.audio_source.is_buffer: while True: chunk = self.audio_source.input.read(ONE_KB) if not chunk: break self.ws_client.send(chunk, websocket.ABNF.OPCODE_BINARY) time.sleep(TEN_MILLISECONDS) self.audio_source.input.close() else: while True: try: if not self.audio_source.input.empty(): chunk = self.audio_source.input.get() self.ws_client.send(chunk, websocket.ABNF.OPCODE_BINARY) time.sleep(TEN_MILLISECONDS) if self.audio_source.input.empty(): if self.audio_source.is_recording: time.sleep(TEN_MILLISECONDS) else: break except Exception: if self.audio_source.is_recording: time.sleep(TEN_MILLISECONDS) else: break time.sleep(TEN_MILLISECONDS) self.ws_client.send(self.build_closing_message(), websocket.ABNF.OPCODE_TEXT) thread.start_new_thread(run, ()) def on_open(self, ws): """ Callback executed when a connection is opened to the server. Handles streaming of audio to the server. :param ws: Websocket client """ self.callback.on_connected() # Send initialization message init_data = self.build_start_message(self.options) self.ws_client.send(json.dumps(init_data).encode('utf8'), websocket.ABNF.OPCODE_TEXT) def on_data(self, ws, message, message_type, fin): """ Callback executed when message is received from the server. :param ws: Websocket client :param message: utf-8 string which we get from the server. :param message_type: Message type which is either ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY :param fin: continue flag. If 0, the data continues. """ try: json_object = json.loads(message) except Exception: self.on_error(ws, 'Unable to parse received message.') if 'error' in json_object: # Only call on_error() if a real error occurred. The STT service sends # {"error" : "No speech detected for 5s"} for valid timeouts, configured by # options.inactivity_timeout error = json_object['error'] if error.startswith(TIMEOUT_PREFIX): self.callback.on_inactivity_timeout(error) else: self.on_error(ws, error) # if uninitialized, receive the initialization response from the server elif 'state' in json_object: if not self.isListening: self.isListening = True self.callback.on_listening() self.send_audio(ws) else: # close the connection self.callback.on_close() ws.close() # if in streaming elif 'results' in json_object or 'speaker_labels' in json_object: hypothesis = '' if 'results' in json_object: hypothesis = json_object['results'][0]['alternatives'][0][ 'transcript'] b_final = (json_object['results'][0]['final'] is True) transcripts = self.extract_transcripts( json_object['results'][0]['alternatives']) if b_final: self.callback.on_transcription(transcripts) self.callback.on_hypothesis(hypothesis) self.callback.on_data(json_object) def on_error(self, ws, error): """ Callback executed when an error is received :param ws: Websocket client :param error: Exception object """ self.callback.on_error(error) def on_close(self, ws): """ Callback executed when websocket connection is closed :param ws: Websocket client """ self.callback.on_close() watson-developer-cloud-2.10.1/watson_developer_cloud/websocket/synthesize_callback.py0000644000076500000240000000316513451407070032776 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SynthesizeCallback(object): def __init__(self): pass def on_connected(self): """ Called when a Websocket connection was made """ pass def on_error(self, error): """ Called when there is an error in the Websocket connection. """ pass def on_content_type(self, content_type): """ Called when the service responds with the format of the audio response """ pass def on_timing_information(self, timing_information): """ Called when the service returns timing information """ pass def on_audio_stream(self, audio_stream): """ Called when the service sends the synthesized audio as a binary stream of data in the indicated format. """ pass def on_data(self, data): """ Called when the service returns results. The data is returned unparsed. """ pass def on_close(self): """ Called when the Websocket connection is closed """ pass watson-developer-cloud-2.10.1/watson_developer_cloud/websocket/audio_source.py0000644000076500000240000000242613451407070031435 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class AudioSource(object): """"Audio source for the speech to text recognize using websocket""" def __init__(self, input, is_recording=False, is_buffer=False): """ :param bytes/Queue input: The audio to transcribe in the format specified by the `Content-Type` header. :param bool is_recording: Used to represent if audio recording is in progress :param bool is_buffer: `True` if audio is a Queue """ self.input = input self.is_recording = is_recording self.is_buffer = is_buffer def completed_recording(self): """ Sets the `is_recording` to False """ self.is_recording = False watson-developer-cloud-2.10.1/watson_developer_cloud/websocket/recognize_abstract_callback.py0000644000076500000240000000322113451407070034432 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RecognizeCallback(object): def __init__(self): pass def on_transcription(self, transcript): """ Called after the service returns the final result for the transcription. """ pass def on_connected(self): """ Called when a Websocket connection was made """ pass def on_error(self, error): """ Called when there is an error in the Websocket connection. """ pass def on_inactivity_timeout(self, error): """ Called when there is an inactivity timeout. """ pass def on_listening(self): """ Called when the service is listening for audio. """ pass def on_hypothesis(self, hypothesis): """ Called when an interim result is received. """ pass def on_data(self, data): """ Called when the service returns results. The data is returned unparsed. """ pass def on_close(self): """ Called when the Websocket connection is closed """ pass watson-developer-cloud-2.10.1/watson_developer_cloud/text_to_speech_adapter_v1.py0000644000076500000240000001366313451407070032116 0ustar erikadsouzastaff00000000000000 # coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from watson_developer_cloud.websocket import SynthesizeCallback, SynthesizeListener import base64 from .text_to_speech_v1 import TextToSpeechV1 from .watson_service import _remove_null_values try: from urllib.parse import urlencode except ImportError: from urllib import urlencode BEARER = 'Bearer' class TextToSpeechV1Adapter(TextToSpeechV1): def synthesize_using_websocket(self, text, synthesize_callback, accept=None, voice=None, timings=None, customization_id=None, http_proxy_host=None, http_proxy_port=None, **kwargs): """ Synthesizes text to spoken audio using web sockets. It supports the use of the SSML element to identify the location of user-specified markers in the audio. It can also return timing information for all strings of the input text. Note:The service processes one request per connection. :param str text: Provides the text that is to be synthesized. The client can pass plain text or text that is annotated with the Speech Synthesis Markup Language (SSML). For more information, see [Specifying input text](https://console.bluemix.net/docs/services/text-to-speech/http.html#input). SSML input can also include the element; see [Specifying an SSML mark](https://console.bluemix.net/docs/services/text-to-speech/word-timing.html#mark). The client can pass a maximum of 5 KB of text with the request. :param SynthesizeCallback synthesize_callback: The callback method for the websocket. :param str accept: Specifies the requested format (MIME type) of the audio. For more information, see [Specifying an audio format](https://console.bluemix.net/docs/services/text-to-speech/http.html#format). In addition to the supported specifications, you can use */* to specify the default audio format, audio/ogg;codecs=opus. :param str voice: The voice to use for synthesis. :param list[str] timings: Specifies that the service is to return word timing information for all strings of the input text. The service returns the start and end time of each string of the input. Specify words as the lone element of the array to request word timings. Specify an empty array or omit the parameter to receive no word timings. For more information, see [Obtaining word timings](https://console.bluemix.net/docs/services/text-to-speech/word-timing.html#timing). Not supported for Japanese input text. :param str customization_id: Specifies the globally unique identifier (GUID) for a custom voice model that is to be used for the synthesis. A custom voice model is guaranteed to work only if it matches the language of the voice that is used for the synthesis. If you include a customization ID, you must call the method with the service credentials of the custom model's owner. Omit the parameter to use the specified voice with no customization. For more information, see [Understanding customization] (https://console.bluemix.net/docs/services/text-to-speech/custom-intro.html#customIntro). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict """ if text is None: raise ValueError('text must be provided') if synthesize_callback is None: raise ValueError('synthesize_callback must be provided') if not isinstance(synthesize_callback, SynthesizeCallback): raise Exception( 'Callback is not a derived class of SynthesizeCallback') headers = {} if self.default_headers is not None: headers = self.default_headers.copy() if 'headers' in kwargs: headers.update(kwargs.get('headers')) if self.token_manager: access_token = self.token_manager.get_token() headers['Authorization'] = '{0} {1}'.format(BEARER, access_token) else: authstring = "{0}:{1}".format(self.username, self.password) base64_authorization = base64.b64encode(authstring.encode('utf-8')).decode('utf-8') headers['Authorization'] = 'Basic {0}'.format(base64_authorization) url = self.url.replace('https:', 'wss:') params = { 'voice': voice, 'customization_id': customization_id, } params = _remove_null_values(params) url += '/v1/synthesize?{0}'.format(urlencode(params)) options = { 'text': text, 'accept': accept, 'timings': timings } options = _remove_null_values(options) SynthesizeListener(options, synthesize_callback, url, headers, http_proxy_host, http_proxy_port, self.verify) watson-developer-cloud-2.10.1/watson_developer_cloud/version.py0000644000076500000240000000002713451437703026454 0ustar erikadsouzastaff00000000000000__version__ = '2.10.1' watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/0000755000076500000240000000000013451440673032654 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/features/0000755000076500000240000000000013451440673034472 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/features/v1/0000755000076500000240000000000013451440673035020 5ustar erikadsouzastaff00000000000000././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/features/v1/__init__.pywatson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/features/v1/__in0000644000076500000240000000375513451407070035653 0ustar erikadsouzastaff00000000000000# coding: utf-8 class Feature(object): def toDict(self): res = {} if not hasattr(self, "_dataTuples"): return res for t in self._dataTuples: self.addKey(t[0], t[1], res) return res def name(self): return self._name def addKey(self, var, name, data_dict): if var is not None: data_dict[name] = var return data_dict class Concepts(Feature): def __init__(self, limit=None): self._dataTuples = [(limit, "limit")] self._name = 'concepts' class Entities(Feature): def __init__(self, limit=None, model=None, emotion=None, sentiment=None): self._dataTuples = [(limit, "limit"), (model, "model"), (emotion, "emotion"), (sentiment, "sentiment")] self._name = 'entities' class Keywords(Feature): def __init__(self, limit=None, emotion=None, sentiment=None): self._dataTuples = [(limit, "limit"), (emotion, "emotion"), (sentiment, "sentiment")] self._name = 'keywords' class Categories(Feature): def __init__(self): self._name = 'categories' class Emotion(Feature): def __init__(self, document=None, targets=None): self._dataTuples = [(document, "document"), (targets, "targets")] self._name = 'emotion' class MetaData(Feature): def __init__(self): self._name = "metadata" class SemanticRoles(Feature): def __init__(self, limit=None, entities=None, keywords=None): self._dataTuples = [(limit, "limit"), (entities, "entities"), (keywords, "keywords")] self._name = "semantic_roles" class Relations(Feature): def __init__(self, model=None): self._dataTuples = [(model, "model")] self._name = 'relations' class Sentiment(Feature): def __init__(self, document=None, targets=None): self._dataTuples = [(document, "document"), (targets, "targets")] self._name = 'sentiment' ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/features/__init__.pywatson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/features/__init_0000644000076500000240000000000013451407070035775 0ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding/__init__.py0000644000076500000240000000000013451407070034745 0ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/watson_developer_cloud/tone_analyzer_v3.py0000644000076500000240000013500213451412250030241 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional and language tones in written text. The service can analyze tone at both the document and sentence levels. You can use the service to understand how your written communications are perceived and then to improve the tone of your communications. Businesses can use the service to learn the tone of their customers' communications and to respond to each customer appropriately, or to understand and improve their customer conversations. **Note:** Request logging is disabled for the Tone Analyzer service. Regardless of whether you set the `X-Watson-Learning-Opt-Out` request header, the service does not log or retain data from requests and responses. """ from __future__ import absolute_import import json from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class ToneAnalyzerV3(WatsonService): """The Tone Analyzer V3 service.""" default_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' def __init__( self, version, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Tone Analyzer service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/tone-analyzer/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='tone_analyzer', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Tone Analyzer') self.version = version ######################### # Methods ######################### def tone(self, tone_input, content_type=None, sentences=None, tones=None, content_language=None, accept_language=None, **kwargs): """ Analyze general tone. Use the general purpose endpoint to analyze the tone of your input content. The service analyzes the content for emotional and language tones. The method always analyzes the tone of the full document; by default, it also analyzes the tone of each individual sentence of the content. You can submit no more than 128 KB of total input content and no more than 1000 individual sentences in JSON, plain text, or HTML format. The service analyzes the first 1000 sentences for document-level analysis and only the first 100 sentences for sentence-level analysis. Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text; for example: `Content-Type: text/plain;charset=utf-8`. For `text/html`, the service removes HTML tags and analyzes only the textual content. **See also:** [Using the general-purpose endpoint](https://cloud.ibm.com/docs/services/tone-analyzer/using-tone.html#using-the-general-purpose-endpoint). :param ToneInput tone_input: JSON, plain text, or HTML input that contains the content to be analyzed. For JSON input, provide an object of type `ToneInput`. :param str content_type: The type of the input. A character encoding can be specified by including a `charset` parameter. For example, 'text/plain;charset=utf-8'. :param bool sentences: Indicates whether the service is to return an analysis of each individual sentence in addition to its analysis of the full document. If `true` (the default), the service returns results for each sentence. :param list[str] tones: **`2017-09-21`:** Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response. **`2016-05-19`:** A comma-separated list of tones for which the service is to return its analysis of the input; the indicated tones apply both to the full document and to individual sentences of the document. You can specify one or more of the valid values. Omit the parameter to request results for all three tones. :param str content_language: The language of the input text for the request: English or French. Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input content must match the specified language. Do not submit content that contains both languages. You can use different languages for **Content-Language** and **Accept-Language**. * **`2017-09-21`:** Accepts `en` or `fr`. * **`2016-05-19`:** Accepts only `en`. :param str accept_language: The desired language of the response. For two-character arguments, regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use different languages for **Content-Language** and **Accept-Language**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if tone_input is None: raise ValueError('tone_input must be provided') if isinstance(tone_input, ToneInput): tone_input = self._convert_model(tone_input, ToneInput) headers = { 'Content-Type': content_type, 'Content-Language': content_language, 'Accept-Language': accept_language } if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=tone_analyzer;service_version=V3;operation_id=tone' params = { 'version': self.version, 'sentences': sentences, 'tones': self._convert_list(tones) } if content_type == 'application/json' and isinstance(tone_input, dict): data = json.dumps(tone_input) else: data = tone_input url = '/v3/tone' response = self.request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) return response def tone_chat(self, utterances, content_language=None, accept_language=None, **kwargs): """ Analyze customer engagement tone. Use the customer engagement endpoint to analyze the tone of customer service and customer support conversations. For each utterance of a conversation, the method reports the most prevalent subset of the following seven tones: sad, frustrated, satisfied, excited, polite, impolite, and sympathetic. If you submit more than 50 utterances, the service returns a warning for the overall content and analyzes only the first 50 utterances. If you submit a single utterance that contains more than 500 characters, the service returns an error for that utterance and does not analyze the utterance. The request fails if all utterances have more than 500 characters. Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8. **See also:** [Using the customer-engagement endpoint](https://cloud.ibm.com/docs/services/tone-analyzer/using-tone-chat.html#using-the-customer-engagement-endpoint). :param list[Utterance] utterances: An array of `Utterance` objects that provides the input content that the service is to analyze. :param str content_language: The language of the input text for the request: English or French. Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input content must match the specified language. Do not submit content that contains both languages. You can use different languages for **Content-Language** and **Accept-Language**. * **`2017-09-21`:** Accepts `en` or `fr`. * **`2016-05-19`:** Accepts only `en`. :param str accept_language: The desired language of the response. For two-character arguments, regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use different languages for **Content-Language** and **Accept-Language**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if utterances is None: raise ValueError('utterances must be provided') utterances = [self._convert_model(x, Utterance) for x in utterances] headers = { 'Content-Language': content_language, 'Accept-Language': accept_language } if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=tone_analyzer;service_version=V3;operation_id=tone_chat' params = {'version': self.version} data = {'utterances': utterances} url = '/v3/tone_chat' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ############################################################################## # Models ############################################################################## class DocumentAnalysis(object): """ An object of type `DocumentAnalysis` that provides the results of the analysis for the full input document. :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the document. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the full document of the input content. The service returns results only for the tones specified with the `tones` parameter of the request. :attr str warning: (optional) **`2017-09-21`:** A warning message if the overall content exceeds 128 KB or contains more than 1000 sentences. The service analyzes only the first 1000 sentences for document-level analysis and the first 100 sentences for sentence-level analysis. **`2016-05-19`:** Not returned. """ def __init__(self, tones=None, tone_categories=None, warning=None): """ Initialize a DocumentAnalysis object. :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the document. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the full document of the input content. The service returns results only for the tones specified with the `tones` parameter of the request. :param str warning: (optional) **`2017-09-21`:** A warning message if the overall content exceeds 128 KB or contains more than 1000 sentences. The service analyzes only the first 1000 sentences for document-level analysis and the first 100 sentences for sentence-level analysis. **`2016-05-19`:** Not returned. """ self.tones = tones self.tone_categories = tone_categories self.warning = warning @classmethod def _from_dict(cls, _dict): """Initialize a DocumentAnalysis object from a json dictionary.""" args = {} if 'tones' in _dict: args['tones'] = [ ToneScore._from_dict(x) for x in (_dict.get('tones')) ] if 'tone_categories' in _dict: args['tone_categories'] = [ ToneCategory._from_dict(x) for x in (_dict.get('tone_categories')) ] if 'warning' in _dict: args['warning'] = _dict.get('warning') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] if hasattr(self, 'tone_categories') and self.tone_categories is not None: _dict['tone_categories'] = [ x._to_dict() for x in self.tone_categories ] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning return _dict def __str__(self): """Return a `str` version of this DocumentAnalysis object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SentenceAnalysis(object): """ SentenceAnalysis. :attr int sentence_id: The unique identifier of a sentence of the input content. The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one. :attr str text: The text of the input sentence. :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the `tones` parameter of the request. :attr int input_from: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** The offset of the first character of the sentence in the overall input content. :attr int input_to: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** The offset of the last character of the sentence in the overall input content. """ def __init__(self, sentence_id, text, tones=None, tone_categories=None, input_from=None, input_to=None): """ Initialize a SentenceAnalysis object. :param int sentence_id: The unique identifier of a sentence of the input content. The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one. :param str text: The text of the input sentence. :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the `tones` parameter of the request. :param int input_from: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** The offset of the first character of the sentence in the overall input content. :param int input_to: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** The offset of the last character of the sentence in the overall input content. """ self.sentence_id = sentence_id self.text = text self.tones = tones self.tone_categories = tone_categories self.input_from = input_from self.input_to = input_to @classmethod def _from_dict(cls, _dict): """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} if 'sentence_id' in _dict: args['sentence_id'] = _dict.get('sentence_id') else: raise ValueError( 'Required property \'sentence_id\' not present in SentenceAnalysis JSON' ) if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in SentenceAnalysis JSON' ) if 'tones' in _dict: args['tones'] = [ ToneScore._from_dict(x) for x in (_dict.get('tones')) ] if 'tone_categories' in _dict: args['tone_categories'] = [ ToneCategory._from_dict(x) for x in (_dict.get('tone_categories')) ] if 'input_from' in _dict: args['input_from'] = _dict.get('input_from') if 'input_to' in _dict: args['input_to'] = _dict.get('input_to') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence_id') and self.sentence_id is not None: _dict['sentence_id'] = self.sentence_id if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] if hasattr(self, 'tone_categories') and self.tone_categories is not None: _dict['tone_categories'] = [ x._to_dict() for x in self.tone_categories ] if hasattr(self, 'input_from') and self.input_from is not None: _dict['input_from'] = self.input_from if hasattr(self, 'input_to') and self.input_to is not None: _dict['input_to'] = self.input_to return _dict def __str__(self): """Return a `str` version of this SentenceAnalysis object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ToneAnalysis(object): """ ToneAnalysis. :attr DocumentAnalysis document_tone: An object of type `DocumentAnalysis` that provides the results of the analysis for the full input document. :attr list[SentenceAnalysis] sentences_tone: (optional) An array of `SentenceAnalysis` objects that provides the results of the analysis for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the `sentences` parameter of the request is set to `false`. """ def __init__(self, document_tone, sentences_tone=None): """ Initialize a ToneAnalysis object. :param DocumentAnalysis document_tone: An object of type `DocumentAnalysis` that provides the results of the analysis for the full input document. :param list[SentenceAnalysis] sentences_tone: (optional) An array of `SentenceAnalysis` objects that provides the results of the analysis for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the `sentences` parameter of the request is set to `false`. """ self.document_tone = document_tone self.sentences_tone = sentences_tone @classmethod def _from_dict(cls, _dict): """Initialize a ToneAnalysis object from a json dictionary.""" args = {} if 'document_tone' in _dict: args['document_tone'] = DocumentAnalysis._from_dict( _dict.get('document_tone')) else: raise ValueError( 'Required property \'document_tone\' not present in ToneAnalysis JSON' ) if 'sentences_tone' in _dict: args['sentences_tone'] = [ SentenceAnalysis._from_dict(x) for x in (_dict.get('sentences_tone')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_tone') and self.document_tone is not None: _dict['document_tone'] = self.document_tone._to_dict() if hasattr(self, 'sentences_tone') and self.sentences_tone is not None: _dict['sentences_tone'] = [ x._to_dict() for x in self.sentences_tone ] return _dict def __str__(self): """Return a `str` version of this ToneAnalysis object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ToneCategory(object): """ ToneCategory. :attr list[ToneScore] tones: An array of `ToneScore` objects that provides the results for the tones of the category. :attr str category_id: The unique, non-localized identifier of the category for the results. The service can return results for the following category IDs: `emotion_tone`, `language_tone`, and `social_tone`. :attr str category_name: The user-visible, localized name of the category. """ def __init__(self, tones, category_id, category_name): """ Initialize a ToneCategory object. :param list[ToneScore] tones: An array of `ToneScore` objects that provides the results for the tones of the category. :param str category_id: The unique, non-localized identifier of the category for the results. The service can return results for the following category IDs: `emotion_tone`, `language_tone`, and `social_tone`. :param str category_name: The user-visible, localized name of the category. """ self.tones = tones self.category_id = category_id self.category_name = category_name @classmethod def _from_dict(cls, _dict): """Initialize a ToneCategory object from a json dictionary.""" args = {} if 'tones' in _dict: args['tones'] = [ ToneScore._from_dict(x) for x in (_dict.get('tones')) ] else: raise ValueError( 'Required property \'tones\' not present in ToneCategory JSON') if 'category_id' in _dict: args['category_id'] = _dict.get('category_id') else: raise ValueError( 'Required property \'category_id\' not present in ToneCategory JSON' ) if 'category_name' in _dict: args['category_name'] = _dict.get('category_name') else: raise ValueError( 'Required property \'category_name\' not present in ToneCategory JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] if hasattr(self, 'category_id') and self.category_id is not None: _dict['category_id'] = self.category_id if hasattr(self, 'category_name') and self.category_name is not None: _dict['category_name'] = self.category_name return _dict def __str__(self): """Return a `str` version of this ToneCategory object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ToneChatScore(object): """ ToneChatScore. :attr float score: The score for the tone in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the utterance. :attr str tone_id: The unique, non-localized identifier of the tone for the results. The service returns results only for tones whose scores meet a minimum threshold of 0.5. :attr str tone_name: The user-visible, localized name of the tone. """ def __init__(self, score, tone_id, tone_name): """ Initialize a ToneChatScore object. :param float score: The score for the tone in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the utterance. :param str tone_id: The unique, non-localized identifier of the tone for the results. The service returns results only for tones whose scores meet a minimum threshold of 0.5. :param str tone_name: The user-visible, localized name of the tone. """ self.score = score self.tone_id = tone_id self.tone_name = tone_name @classmethod def _from_dict(cls, _dict): """Initialize a ToneChatScore object from a json dictionary.""" args = {} if 'score' in _dict: args['score'] = _dict.get('score') else: raise ValueError( 'Required property \'score\' not present in ToneChatScore JSON') if 'tone_id' in _dict: args['tone_id'] = _dict.get('tone_id') else: raise ValueError( 'Required property \'tone_id\' not present in ToneChatScore JSON' ) if 'tone_name' in _dict: args['tone_name'] = _dict.get('tone_name') else: raise ValueError( 'Required property \'tone_name\' not present in ToneChatScore JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'tone_id') and self.tone_id is not None: _dict['tone_id'] = self.tone_id if hasattr(self, 'tone_name') and self.tone_name is not None: _dict['tone_name'] = self.tone_name return _dict def __str__(self): """Return a `str` version of this ToneChatScore object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ToneInput(object): """ ToneInput. :attr str text: The input content that the service is to analyze. """ def __init__(self, text): """ Initialize a ToneInput object. :param str text: The input content that the service is to analyze. """ self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a ToneInput object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in ToneInput JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this ToneInput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ToneScore(object): """ ToneScore. :attr float score: The score for the tone. * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the content. * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. A score less than 0.5 indicates that the tone is unlikely to be perceived in the content; a score greater than 0.75 indicates a high likelihood that the tone is perceived. :attr str tone_id: The unique, non-localized identifier of the tone. * **`2017-09-21`:** The service can return results for the following tone IDs: `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, `confident`, and `tentative` (language tones). The service returns results only for tones whose scores meet a minimum threshold of 0.5. * **`2016-05-19`:** The service can return results for the following tone IDs of the different categories: for the `emotion` category: `anger`, `disgust`, `fear`, `joy`, and `sadness`; for the `language` category: `analytical`, `confident`, and `tentative`; for the `social` category: `openness_big5`, `conscientiousness_big5`, `extraversion_big5`, `agreeableness_big5`, and `emotional_range_big5`. The service returns scores for all tones of a category, regardless of their values. :attr str tone_name: The user-visible, localized name of the tone. """ def __init__(self, score, tone_id, tone_name): """ Initialize a ToneScore object. :param float score: The score for the tone. * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the content. * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. A score less than 0.5 indicates that the tone is unlikely to be perceived in the content; a score greater than 0.75 indicates a high likelihood that the tone is perceived. :param str tone_id: The unique, non-localized identifier of the tone. * **`2017-09-21`:** The service can return results for the following tone IDs: `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, `confident`, and `tentative` (language tones). The service returns results only for tones whose scores meet a minimum threshold of 0.5. * **`2016-05-19`:** The service can return results for the following tone IDs of the different categories: for the `emotion` category: `anger`, `disgust`, `fear`, `joy`, and `sadness`; for the `language` category: `analytical`, `confident`, and `tentative`; for the `social` category: `openness_big5`, `conscientiousness_big5`, `extraversion_big5`, `agreeableness_big5`, and `emotional_range_big5`. The service returns scores for all tones of a category, regardless of their values. :param str tone_name: The user-visible, localized name of the tone. """ self.score = score self.tone_id = tone_id self.tone_name = tone_name @classmethod def _from_dict(cls, _dict): """Initialize a ToneScore object from a json dictionary.""" args = {} if 'score' in _dict: args['score'] = _dict.get('score') else: raise ValueError( 'Required property \'score\' not present in ToneScore JSON') if 'tone_id' in _dict: args['tone_id'] = _dict.get('tone_id') else: raise ValueError( 'Required property \'tone_id\' not present in ToneScore JSON') if 'tone_name' in _dict: args['tone_name'] = _dict.get('tone_name') else: raise ValueError( 'Required property \'tone_name\' not present in ToneScore JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'tone_id') and self.tone_id is not None: _dict['tone_id'] = self.tone_id if hasattr(self, 'tone_name') and self.tone_name is not None: _dict['tone_name'] = self.tone_name return _dict def __str__(self): """Return a `str` version of this ToneScore object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Utterance(object): """ Utterance. :attr str text: An utterance contributed by a user in the conversation that is to be analyzed. The utterance can contain multiple sentences. :attr str user: (optional) A string that identifies the user who contributed the utterance specified by the `text` parameter. """ def __init__(self, text, user=None): """ Initialize a Utterance object. :param str text: An utterance contributed by a user in the conversation that is to be analyzed. The utterance can contain multiple sentences. :param str user: (optional) A string that identifies the user who contributed the utterance specified by the `text` parameter. """ self.text = text self.user = user @classmethod def _from_dict(cls, _dict): """Initialize a Utterance object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in Utterance JSON') if 'user' in _dict: args['user'] = _dict.get('user') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'user') and self.user is not None: _dict['user'] = self.user return _dict def __str__(self): """Return a `str` version of this Utterance object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class UtteranceAnalyses(object): """ UtteranceAnalyses. :attr list[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` objects that provides the results for each utterance of the input. :attr str warning: (optional) **`2017-09-21`:** A warning message if the content contains more than 50 utterances. The service analyzes only the first 50 utterances. **`2016-05-19`:** Not returned. """ def __init__(self, utterances_tone, warning=None): """ Initialize a UtteranceAnalyses object. :param list[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` objects that provides the results for each utterance of the input. :param str warning: (optional) **`2017-09-21`:** A warning message if the content contains more than 50 utterances. The service analyzes only the first 50 utterances. **`2016-05-19`:** Not returned. """ self.utterances_tone = utterances_tone self.warning = warning @classmethod def _from_dict(cls, _dict): """Initialize a UtteranceAnalyses object from a json dictionary.""" args = {} if 'utterances_tone' in _dict: args['utterances_tone'] = [ UtteranceAnalysis._from_dict(x) for x in (_dict.get('utterances_tone')) ] else: raise ValueError( 'Required property \'utterances_tone\' not present in UtteranceAnalyses JSON' ) if 'warning' in _dict: args['warning'] = _dict.get('warning') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'utterances_tone') and self.utterances_tone is not None: _dict['utterances_tone'] = [ x._to_dict() for x in self.utterances_tone ] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning return _dict def __str__(self): """Return a `str` version of this UtteranceAnalyses object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class UtteranceAnalysis(object): """ UtteranceAnalysis. :attr int utterance_id: The unique identifier of the utterance. The first utterance has ID 0, and the ID of each subsequent utterance is incremented by one. :attr str utterance_text: The text of the utterance. :attr list[ToneChatScore] tones: An array of `ToneChatScore` objects that provides results for the most prevalent tones of the utterance. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. :attr str error: (optional) **`2017-09-21`:** An error message if the utterance contains more than 500 characters. The service does not analyze the utterance. **`2016-05-19`:** Not returned. """ def __init__(self, utterance_id, utterance_text, tones, error=None): """ Initialize a UtteranceAnalysis object. :param int utterance_id: The unique identifier of the utterance. The first utterance has ID 0, and the ID of each subsequent utterance is incremented by one. :param str utterance_text: The text of the utterance. :param list[ToneChatScore] tones: An array of `ToneChatScore` objects that provides results for the most prevalent tones of the utterance. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. :param str error: (optional) **`2017-09-21`:** An error message if the utterance contains more than 500 characters. The service does not analyze the utterance. **`2016-05-19`:** Not returned. """ self.utterance_id = utterance_id self.utterance_text = utterance_text self.tones = tones self.error = error @classmethod def _from_dict(cls, _dict): """Initialize a UtteranceAnalysis object from a json dictionary.""" args = {} if 'utterance_id' in _dict: args['utterance_id'] = _dict.get('utterance_id') else: raise ValueError( 'Required property \'utterance_id\' not present in UtteranceAnalysis JSON' ) if 'utterance_text' in _dict: args['utterance_text'] = _dict.get('utterance_text') else: raise ValueError( 'Required property \'utterance_text\' not present in UtteranceAnalysis JSON' ) if 'tones' in _dict: args['tones'] = [ ToneChatScore._from_dict(x) for x in (_dict.get('tones')) ] else: raise ValueError( 'Required property \'tones\' not present in UtteranceAnalysis JSON' ) if 'error' in _dict: args['error'] = _dict.get('error') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'utterance_id') and self.utterance_id is not None: _dict['utterance_id'] = self.utterance_id if hasattr(self, 'utterance_text') and self.utterance_text is not None: _dict['utterance_text'] = self.utterance_text if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] if hasattr(self, 'error') and self.error is not None: _dict['error'] = self.error return _dict def __str__(self): """Return a `str` version of this UtteranceAnalysis object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/assistant_v2.py0000644000076500000240000022151713451412113027404 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and integrated dialog tools to create conversation flows between your apps and your users. """ from __future__ import absolute_import import json from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class AssistantV2(WatsonService): """The Assistant V2 service.""" default_url = 'https://gateway.watsonplatform.net/assistant/api' def __init__( self, version, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Assistant service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/assistant/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='conversation', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Assistant') self.version = version ######################### # Sessions ######################### def create_session(self, assistant_id, **kwargs): """ Create a session. Create a new session. A session is used to send user input to a skill and receive responses. It also maintains the state of the conversation. :param str assistant_id: Unique identifier of the assistant. You can find the assistant ID of an assistant on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the [documentation](https://console.bluemix.net/docs/services/assistant/create-assistant.html#creating-assistants). **Note:** Currently, the v2 API does not support creating assistants. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if assistant_id is None: raise ValueError('assistant_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V2;operation_id=create_session' params = {'version': self.version} url = '/v2/assistants/{0}/sessions'.format( *self._encode_path_vars(assistant_id)) response = self.request( method='POST', url=url, headers=headers, params=params, accept_json=True) return response def delete_session(self, assistant_id, session_id, **kwargs): """ Delete session. Deletes a session explicitly before it times out. :param str assistant_id: Unique identifier of the assistant. You can find the assistant ID of an assistant on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the [documentation](https://console.bluemix.net/docs/services/assistant/create-assistant.html#creating-assistants). **Note:** Currently, the v2 API does not support creating assistants. :param str session_id: Unique identifier of the session. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if assistant_id is None: raise ValueError('assistant_id must be provided') if session_id is None: raise ValueError('session_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V2;operation_id=delete_session' params = {'version': self.version} url = '/v2/assistants/{0}/sessions/{1}'.format( *self._encode_path_vars(assistant_id, session_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Message ######################### def message(self, assistant_id, session_id, input=None, context=None, **kwargs): """ Send user input to assistant. Send user input to an assistant and receive a response. There is no rate limit for this operation. :param str assistant_id: Unique identifier of the assistant. You can find the assistant ID of an assistant on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the [documentation](https://console.bluemix.net/docs/services/assistant/create-assistant.html#creating-assistants). **Note:** Currently, the v2 API does not support creating assistants. :param str session_id: Unique identifier of the session. :param MessageInput input: An input object that includes the input text. :param MessageContext context: State information for the conversation. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if assistant_id is None: raise ValueError('assistant_id must be provided') if session_id is None: raise ValueError('session_id must be provided') if input is not None: input = self._convert_model(input, MessageInput) if context is not None: context = self._convert_model(context, MessageContext) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V2;operation_id=message' params = {'version': self.version} data = {'input': input, 'context': context} url = '/v2/assistants/{0}/sessions/{1}/message'.format( *self._encode_path_vars(assistant_id, session_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ############################################################################## # Models ############################################################################## class CaptureGroup(object): """ CaptureGroup. :attr str group: A recognized capture group for the entity. :attr list[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ def __init__(self, group, location=None): """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. :param list[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a CaptureGroup object from a json dictionary.""" args = {} if 'group' in _dict: args['group'] = _dict.get('group') else: raise ValueError( 'Required property \'group\' not present in CaptureGroup JSON') if 'location' in _dict: args['location'] = _dict.get('location') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'group') and self.group is not None: _dict['group'] = self.group if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location return _dict def __str__(self): """Return a `str` version of this CaptureGroup object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogLogMessage(object): """ Dialog log message details. :attr str level: The severity of the log message. :attr str message: The text of the log message. """ def __init__(self, level, message): """ Initialize a DialogLogMessage object. :param str level: The severity of the log message. :param str message: The text of the log message. """ self.level = level self.message = message @classmethod def _from_dict(cls, _dict): """Initialize a DialogLogMessage object from a json dictionary.""" args = {} if 'level' in _dict: args['level'] = _dict.get('level') else: raise ValueError( 'Required property \'level\' not present in DialogLogMessage JSON' ) if 'message' in _dict: args['message'] = _dict.get('message') else: raise ValueError( 'Required property \'message\' not present in DialogLogMessage JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'level') and self.level is not None: _dict['level'] = self.level if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message return _dict def __str__(self): """Return a `str` version of this DialogLogMessage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeAction(object): """ DialogNodeAction. :attr str name: The name of the action. :attr str action_type: (optional) The type of action to invoke. :attr object parameters: (optional) A map of key/value pairs to be provided to the action. :attr str result_variable: The location in the dialog context where the result of the action is stored. :attr str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ def __init__(self, name, result_variable, action_type=None, parameters=None, credentials=None): """ Initialize a DialogNodeAction object. :param str name: The name of the action. :param str result_variable: The location in the dialog context where the result of the action is stored. :param str action_type: (optional) The type of action to invoke. :param object parameters: (optional) A map of key/value pairs to be provided to the action. :param str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ self.name = name self.action_type = action_type self.parameters = parameters self.result_variable = result_variable self.credentials = credentials @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeAction object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) if 'type' in _dict or 'action_type' in _dict: args['action_type'] = _dict.get('type') or _dict.get('action_type') if 'parameters' in _dict: args['parameters'] = _dict.get('parameters') if 'result_variable' in _dict: args['result_variable'] = _dict.get('result_variable') else: raise ValueError( 'Required property \'result_variable\' not present in DialogNodeAction JSON' ) if 'credentials' in _dict: args['credentials'] = _dict.get('credentials') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'action_type') and self.action_type is not None: _dict['type'] = self.action_type if hasattr(self, 'parameters') and self.parameters is not None: _dict['parameters'] = self.parameters if hasattr(self, 'result_variable') and self.result_variable is not None: _dict['result_variable'] = self.result_variable if hasattr(self, 'credentials') and self.credentials is not None: _dict['credentials'] = self.credentials return _dict def __str__(self): """Return a `str` version of this DialogNodeAction object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutputOptionsElement(object): """ DialogNodeOutputOptionsElement. :attr str label: The user-facing label for the option. :attr DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding option. """ def __init__(self, label, value): """ Initialize a DialogNodeOutputOptionsElement object. :param str label: The user-facing label for the option. :param DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding option. """ self.label = label self.value = value @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = _dict.get('label') else: raise ValueError( 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) if 'value' in _dict: args['value'] = DialogNodeOutputOptionsElementValue._from_dict( _dict.get('value')) else: raise ValueError( 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value._to_dict() return _dict def __str__(self): """Return a `str` version of this DialogNodeOutputOptionsElement object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutputOptionsElementValue(object): """ An object defining the message input to be sent to the assistant if the user selects the corresponding option. :attr MessageInput input: (optional) An input object that includes the input text. """ def __init__(self, input=None): """ Initialize a DialogNodeOutputOptionsElementValue object. :param MessageInput input: (optional) An input object that includes the input text. """ self.input = input @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: _dict['input'] = self.input._to_dict() return _dict def __str__(self): """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodesVisited(object): """ DialogNodesVisited. :attr str dialog_node: (optional) A dialog node that was triggered during processing of the input message. :attr str title: (optional) The title of the dialog node. :attr str conditions: (optional) The conditions that trigger the dialog node. """ def __init__(self, dialog_node=None, title=None, conditions=None): """ Initialize a DialogNodesVisited object. :param str dialog_node: (optional) A dialog node that was triggered during processing of the input message. :param str title: (optional) The title of the dialog node. :param str conditions: (optional) The conditions that trigger the dialog node. """ self.dialog_node = dialog_node self.title = title self.conditions = conditions @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodesVisited object from a json dictionary.""" args = {} if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') if 'title' in _dict: args['title'] = _dict.get('title') if 'conditions' in _dict: args['conditions'] = _dict.get('conditions') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'conditions') and self.conditions is not None: _dict['conditions'] = self.conditions return _dict def __str__(self): """Return a `str` version of this DialogNodesVisited object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogRuntimeResponseGeneric(object): """ DialogRuntimeResponseGeneric. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available for Premium users. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during the pause. :attr str source: (optional) The URL of the image. :attr str title: (optional) The title to show before the response. :attr str description: (optional) The description to show with the the response. :attr str preference: (optional) The preferred type of control to display. :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :attr str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. :attr list[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. """ def __init__(self, response_type, text=None, time=None, typing=None, source=None, title=None, description=None, preference=None, options=None, message_to_human_agent=None, topic=None, suggestions=None): """ Initialize a DialogRuntimeResponseGeneric object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available for Premium users. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event during the pause. :param str source: (optional) The URL of the image. :param str title: (optional) The title to show before the response. :param str description: (optional) The description to show with the the response. :param str preference: (optional) The preferred type of control to display. :param list[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :param str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. :param list[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. """ self.response_type = response_type self.text = text self.time = time self.typing = typing self.source = source self.title = title self.description = description self.preference = preference self.options = options self.message_to_human_agent = message_to_human_agent self.topic = topic self.suggestions = suggestions @classmethod def _from_dict(cls, _dict): """Initialize a DialogRuntimeResponseGeneric object from a json dictionary.""" args = {} if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: raise ValueError( 'Required property \'response_type\' not present in DialogRuntimeResponseGeneric JSON' ) if 'text' in _dict: args['text'] = _dict.get('text') if 'time' in _dict: args['time'] = _dict.get('time') if 'typing' in _dict: args['typing'] = _dict.get('typing') if 'source' in _dict: args['source'] = _dict.get('source') if 'title' in _dict: args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') if 'preference' in _dict: args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ DialogNodeOutputOptionsElement._from_dict(x) for x in (_dict.get('options')) ] if 'message_to_human_agent' in _dict: args['message_to_human_agent'] = _dict.get('message_to_human_agent') if 'topic' in _dict: args['topic'] = _dict.get('topic') if 'suggestions' in _dict: args['suggestions'] = [ DialogSuggestion._from_dict(x) for x in (_dict.get('suggestions')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'time') and self.time is not None: _dict['time'] = self.time if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: _dict['options'] = [x._to_dict() for x in self.options] if hasattr(self, 'message_to_human_agent' ) and self.message_to_human_agent is not None: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'suggestions') and self.suggestions is not None: _dict['suggestions'] = [x._to_dict() for x in self.suggestions] return _dict def __str__(self): """Return a `str` version of this DialogRuntimeResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogSuggestion(object): """ DialogSuggestion. :attr str label: The user-facing label for the disambiguation option. This label is taken from the **user_label** property of the corresponding dialog node. :attr DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. :attr object output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. """ def __init__(self, label, value, output=None): """ Initialize a DialogSuggestion object. :param str label: The user-facing label for the disambiguation option. This label is taken from the **user_label** property of the corresponding dialog node. :param DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. :param object output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. """ self.label = label self.value = value self.output = output @classmethod def _from_dict(cls, _dict): """Initialize a DialogSuggestion object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = _dict.get('label') else: raise ValueError( 'Required property \'label\' not present in DialogSuggestion JSON' ) if 'value' in _dict: args['value'] = DialogSuggestionValue._from_dict(_dict.get('value')) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' ) if 'output' in _dict: args['output'] = _dict.get('output') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value._to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output return _dict def __str__(self): """Return a `str` version of this DialogSuggestion object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogSuggestionValue(object): """ An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. :attr MessageInput input: (optional) An input object that includes the input text. """ def __init__(self, input=None): """ Initialize a DialogSuggestionValue object. :param MessageInput input: (optional) An input object that includes the input text. """ self.input = input @classmethod def _from_dict(cls, _dict): """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: _dict['input'] = self.input._to_dict() return _dict def __str__(self): """Return a `str` version of this DialogSuggestionValue object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageContext(object): """ State information for the conversation. :attr MessageContextGlobal global_: (optional) Contains information that can be shared by all skills within the Assistant. :attr MessageContextSkills skills: (optional) Contains information specific to particular skills within the Assistant. """ def __init__(self, global_=None, skills=None): """ Initialize a MessageContext object. :param MessageContextGlobal global_: (optional) Contains information that can be shared by all skills within the Assistant. :param MessageContextSkills skills: (optional) Contains information specific to particular skills within the Assistant. """ self.global_ = global_ self.skills = skills @classmethod def _from_dict(cls, _dict): """Initialize a MessageContext object from a json dictionary.""" args = {} if 'global' in _dict: args['global_'] = MessageContextGlobal._from_dict( _dict.get('global')) if 'skills' in _dict: args['skills'] = MessageContextSkills._from_dict( _dict.get('skills')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'global_') and self.global_ is not None: _dict['global'] = self.global_._to_dict() if hasattr(self, 'skills') and self.skills is not None: _dict['skills'] = self.skills._to_dict() return _dict def __str__(self): """Return a `str` version of this MessageContext object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageContextGlobal(object): """ Contains information that can be shared by all skills within the Assistant. :attr MessageContextGlobalSystem system: (optional) Properties that are shared by all skills used by the assistant. """ def __init__(self, system=None): """ Initialize a MessageContextGlobal object. :param MessageContextGlobalSystem system: (optional) Properties that are shared by all skills used by the assistant. """ self.system = system @classmethod def _from_dict(cls, _dict): """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} if 'system' in _dict: args['system'] = MessageContextGlobalSystem._from_dict( _dict.get('system')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'system') and self.system is not None: _dict['system'] = self.system._to_dict() return _dict def __str__(self): """Return a `str` version of this MessageContextGlobal object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageContextGlobalSystem(object): """ Properties that are shared by all skills used by the assistant. :attr str timezone: (optional) The user time zone. The assistant uses the time zone to correctly resolve relative time references. :attr str user_id: (optional) A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For Plus and Premium plans, this user ID is used to identify unique users for billing purposes. This string cannot contain carriage return, newline, or tab characters. :attr int turn_count: (optional) A counter that is automatically incremented with each turn of the conversation. A value of 1 indicates that this is the the first turn of a new conversation, which can affect the behavior of some skills. """ def __init__(self, timezone=None, user_id=None, turn_count=None): """ Initialize a MessageContextGlobalSystem object. :param str timezone: (optional) The user time zone. The assistant uses the time zone to correctly resolve relative time references. :param str user_id: (optional) A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For Plus and Premium plans, this user ID is used to identify unique users for billing purposes. This string cannot contain carriage return, newline, or tab characters. :param int turn_count: (optional) A counter that is automatically incremented with each turn of the conversation. A value of 1 indicates that this is the the first turn of a new conversation, which can affect the behavior of some skills. """ self.timezone = timezone self.user_id = user_id self.turn_count = turn_count @classmethod def _from_dict(cls, _dict): """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} if 'timezone' in _dict: args['timezone'] = _dict.get('timezone') if 'user_id' in _dict: args['user_id'] = _dict.get('user_id') if 'turn_count' in _dict: args['turn_count'] = _dict.get('turn_count') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'timezone') and self.timezone is not None: _dict['timezone'] = self.timezone if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id if hasattr(self, 'turn_count') and self.turn_count is not None: _dict['turn_count'] = self.turn_count return _dict def __str__(self): """Return a `str` version of this MessageContextGlobalSystem object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageContextSkill(object): """ Contains information specific to a particular skill within the Assistant. :attr str user_defined: (optional) Arbitrary variables that can be read and written to by a particular skill within the Assistant. """ def __init__(self, user_defined=None): """ Initialize a MessageContextSkill object. :param str user_defined: (optional) Arbitrary variables that can be read and written to by a particular skill within the Assistant. """ self.user_defined = user_defined @classmethod def _from_dict(cls, _dict): """Initialize a MessageContextSkill object from a json dictionary.""" args = {} if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined return _dict def __str__(self): """Return a `str` version of this MessageContextSkill object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageContextSkills(object): """ Contains information specific to particular skills within the Assistant. """ def __init__(self, **kwargs): """ Initialize a MessageContextSkills object. :param **kwargs: (optional) Any additional properties. """ for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a MessageContextSkills object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {} if not hasattr(self, '_additionalProperties'): super(MessageContextSkills, self).__setattr__( '_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(MessageContextSkills, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this MessageContextSkills object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageInput(object): """ An input object that includes the input text. :attr str message_type: (optional) The type of user input. Currently, only text input is supported. :attr str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. :attr MessageInputOptions options: (optional) Optional properties that control how the assistant responds. :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :attr str suggestion_id: (optional) For internal use only. """ def __init__(self, message_type=None, text=None, options=None, intents=None, entities=None, suggestion_id=None): """ Initialize a MessageInput object. :param str message_type: (optional) The type of user input. Currently, only text input is supported. :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. :param MessageInputOptions options: (optional) Optional properties that control how the assistant responds. :param list[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. :param list[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :param str suggestion_id: (optional) For internal use only. """ self.message_type = message_type self.text = text self.options = options self.intents = intents self.entities = entities self.suggestion_id = suggestion_id @classmethod def _from_dict(cls, _dict): """Initialize a MessageInput object from a json dictionary.""" args = {} if 'message_type' in _dict: args['message_type'] = _dict.get('message_type') if 'text' in _dict: args['text'] = _dict.get('text') if 'options' in _dict: args['options'] = MessageInputOptions._from_dict( _dict.get('options')) if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'entities' in _dict: args['entities'] = [ RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'message_type') and self.message_type is not None: _dict['message_type'] = self.message_type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'options') and self.options is not None: _dict['options'] = self.options._to_dict() if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id return _dict def __str__(self): """Return a `str` version of this MessageInput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageInputOptions(object): """ Optional properties that control how the assistant responds. :attr bool debug: (optional) Whether to return additional diagnostic information. Set to `true` to return additional information under the `output.debug` key. :attr bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. :attr bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. :attr bool return_context: (optional) Whether to return session context with the response. If you specify `true`, the response will include the `context` property. """ def __init__(self, debug=None, restart=None, alternate_intents=None, return_context=None): """ Initialize a MessageInputOptions object. :param bool debug: (optional) Whether to return additional diagnostic information. Set to `true` to return additional information under the `output.debug` key. :param bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. :param bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. :param bool return_context: (optional) Whether to return session context with the response. If you specify `true`, the response will include the `context` property. """ self.debug = debug self.restart = restart self.alternate_intents = alternate_intents self.return_context = return_context @classmethod def _from_dict(cls, _dict): """Initialize a MessageInputOptions object from a json dictionary.""" args = {} if 'debug' in _dict: args['debug'] = _dict.get('debug') if 'restart' in _dict: args['restart'] = _dict.get('restart') if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') if 'return_context' in _dict: args['return_context'] = _dict.get('return_context') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'debug') and self.debug is not None: _dict['debug'] = self.debug if hasattr(self, 'restart') and self.restart is not None: _dict['restart'] = self.restart if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'return_context') and self.return_context is not None: _dict['return_context'] = self.return_context return _dict def __str__(self): """Return a `str` version of this MessageInputOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageOutput(object): """ Assistant output to be rendered or processed by the client. :attr list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. :attr list[RuntimeIntent] intents: (optional) An array of intents recognized in the user input, sorted in descending order of confidence. :attr list[RuntimeEntity] entities: (optional) An array of entities identified in the user input. :attr list[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. :attr MessageOutputDebug debug: (optional) Additional detailed information about a message response and how it was generated. :attr object user_defined: (optional) An object containing any custom properties included in the response. This object includes any arbitrary properties defined in the dialog JSON editor as part of the dialog node output. """ def __init__(self, generic=None, intents=None, entities=None, actions=None, debug=None, user_defined=None): """ Initialize a MessageOutput object. :param list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. :param list[RuntimeIntent] intents: (optional) An array of intents recognized in the user input, sorted in descending order of confidence. :param list[RuntimeEntity] entities: (optional) An array of entities identified in the user input. :param list[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. :param MessageOutputDebug debug: (optional) Additional detailed information about a message response and how it was generated. :param object user_defined: (optional) An object containing any custom properties included in the response. This object includes any arbitrary properties defined in the dialog JSON editor as part of the dialog node output. """ self.generic = generic self.intents = intents self.entities = entities self.actions = actions self.debug = debug self.user_defined = user_defined @classmethod def _from_dict(cls, _dict): """Initialize a MessageOutput object from a json dictionary.""" args = {} if 'generic' in _dict: args['generic'] = [ DialogRuntimeResponseGeneric._from_dict(x) for x in (_dict.get('generic')) ] if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'entities' in _dict: args['entities'] = [ RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) ] if 'actions' in _dict: args['actions'] = [ DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) ] if 'debug' in _dict: args['debug'] = MessageOutputDebug._from_dict(_dict.get('debug')) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: _dict['generic'] = [x._to_dict() for x in self.generic] if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'actions') and self.actions is not None: _dict['actions'] = [x._to_dict() for x in self.actions] if hasattr(self, 'debug') and self.debug is not None: _dict['debug'] = self.debug._to_dict() if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined return _dict def __str__(self): """Return a `str` version of this MessageOutput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageOutputDebug(object): """ Additional detailed information about a message response and how it was generated. :attr list[DialogNodesVisited] nodes_visited: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. :attr list[DialogLogMessage] log_messages: (optional) An array of up to 50 messages logged with the request. :attr bool branch_exited: (optional) Assistant sets this to true when this message response concludes or interrupts a dialog. :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` by the Assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. """ def __init__(self, nodes_visited=None, log_messages=None, branch_exited=None, branch_exited_reason=None): """ Initialize a MessageOutputDebug object. :param list[DialogNodesVisited] nodes_visited: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. :param list[DialogLogMessage] log_messages: (optional) An array of up to 50 messages logged with the request. :param bool branch_exited: (optional) Assistant sets this to true when this message response concludes or interrupts a dialog. :param str branch_exited_reason: (optional) When `branch_exited` is set to `true` by the Assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. """ self.nodes_visited = nodes_visited self.log_messages = log_messages self.branch_exited = branch_exited self.branch_exited_reason = branch_exited_reason @classmethod def _from_dict(cls, _dict): """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} if 'nodes_visited' in _dict: args['nodes_visited'] = [ DialogNodesVisited._from_dict(x) for x in (_dict.get('nodes_visited')) ] if 'log_messages' in _dict: args['log_messages'] = [ DialogLogMessage._from_dict(x) for x in (_dict.get('log_messages')) ] if 'branch_exited' in _dict: args['branch_exited'] = _dict.get('branch_exited') if 'branch_exited_reason' in _dict: args['branch_exited_reason'] = _dict.get('branch_exited_reason') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: _dict['nodes_visited'] = [x._to_dict() for x in self.nodes_visited] if hasattr(self, 'log_messages') and self.log_messages is not None: _dict['log_messages'] = [x._to_dict() for x in self.log_messages] if hasattr(self, 'branch_exited') and self.branch_exited is not None: _dict['branch_exited'] = self.branch_exited if hasattr(self, 'branch_exited_reason' ) and self.branch_exited_reason is not None: _dict['branch_exited_reason'] = self.branch_exited_reason return _dict def __str__(self): """Return a `str` version of this MessageOutputDebug object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageResponse(object): """ A response from the Watson Assistant service. :attr MessageOutput output: Assistant output to be rendered or processed by the client. :attr MessageContext context: (optional) State information for the conversation. """ def __init__(self, output, context=None): """ Initialize a MessageResponse object. :param MessageOutput output: Assistant output to be rendered or processed by the client. :param MessageContext context: (optional) State information for the conversation. """ self.output = output self.context = context @classmethod def _from_dict(cls, _dict): """Initialize a MessageResponse object from a json dictionary.""" args = {} if 'output' in _dict: args['output'] = MessageOutput._from_dict(_dict.get('output')) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) if 'context' in _dict: args['context'] = MessageContext._from_dict(_dict.get('context')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output._to_dict() if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context._to_dict() return _dict def __str__(self): """Return a `str` version of this MessageResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RuntimeEntity(object): """ A term from the request that was identified as an entity. :attr str entity: An entity detected in the input. :attr list[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :attr str value: The term in the input text that was recognized as an entity value. :attr float confidence: (optional) A decimal percentage that represents Watson's confidence in the entity. :attr object metadata: (optional) Any metadata for the entity. :attr list[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ def __init__(self, entity, location, value, confidence=None, metadata=None, groups=None): """ Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. :param list[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :param str value: The term in the input text that was recognized as an entity value. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the entity. :param object metadata: (optional) Any metadata for the entity. :param list[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ self.entity = entity self.location = location self.value = value self.confidence = confidence self.metadata = metadata self.groups = groups @classmethod def _from_dict(cls, _dict): """Initialize a RuntimeEntity object from a json dictionary.""" args = {} if 'entity' in _dict: args['entity'] = _dict.get('entity') else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) if 'location' in _dict: args['location'] = _dict.get('location') else: raise ValueError( 'Required property \'location\' not present in RuntimeEntity JSON' ) if 'value' in _dict: args['value'] = _dict.get('value') else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'groups' in _dict: args['groups'] = [ CaptureGroup._from_dict(x) for x in (_dict.get('groups')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entity') and self.entity is not None: _dict['entity'] = self.entity if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'groups') and self.groups is not None: _dict['groups'] = [x._to_dict() for x in self.groups] return _dict def __str__(self): """Return a `str` version of this RuntimeEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RuntimeIntent(object): """ An intent identified in the user input. :attr str intent: The name of the recognized intent. :attr float confidence: A decimal percentage that represents Watson's confidence in the intent. """ def __init__(self, intent, confidence): """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. :param float confidence: A decimal percentage that represents Watson's confidence in the intent. """ self.intent = intent self.confidence = confidence @classmethod def _from_dict(cls, _dict): """Initialize a RuntimeIntent object from a json dictionary.""" args = {} if 'intent' in _dict: args['intent'] = _dict.get('intent') else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: raise ValueError( 'Required property \'confidence\' not present in RuntimeIntent JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intent') and self.intent is not None: _dict['intent'] = self.intent if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence return _dict def __str__(self): """Return a `str` version of this RuntimeIntent object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SessionResponse(object): """ SessionResponse. :attr str session_id: The session ID. """ def __init__(self, session_id): """ Initialize a SessionResponse object. :param str session_id: The session ID. """ self.session_id = session_id @classmethod def _from_dict(cls, _dict): """Initialize a SessionResponse object from a json dictionary.""" args = {} if 'session_id' in _dict: args['session_id'] = _dict.get('session_id') else: raise ValueError( 'Required property \'session_id\' not present in SessionResponse JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'session_id') and self.session_id is not None: _dict['session_id'] = self.session_id return _dict def __str__(self): """Return a `str` version of this SessionResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/authorization_v1.py0000644000076500000240000000404613451412143030271 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The v1 Authorization "service" that enables developers to retrieve a temporary access token """ from watson_developer_cloud.watson_service import WatsonService from .utils import deprecated try: import urllib.parse as urlparse # Python 3 except ImportError: import urlparse # Python 2 @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class AuthorizationV1(WatsonService): """ Generates tokens, which can be used client-side to avoid exposing the service credentials. Tokens are valid for 1 hour and are sent using the `X-Watson-Authorization-Token` header. """ default_url = "https://stream.watsonplatform.net/authorization/api" def __init__(self, url=default_url, username=None, password=None, use_vcap_services=True): WatsonService.__init__( self, 'authorization', url, username, password, use_vcap_services, display_name='authorization') def get_token(self, url): """ Retrieves a temporary access token """ # A hack to avoid url-encoding the url, since the authorization service # doesn't work with correctly encoded urls parsed_url = urlparse.urlsplit(url) parsed_url = parsed_url._replace(path='/authorization/api') self.url = urlparse.urlunsplit(parsed_url) response = self.request(method='GET', url='/v1/token?url=' + url) return response.result.text watson-developer-cloud-2.10.1/watson_developer_cloud/visual_recognition_v3.py0000644000076500000240000021536413451412272031310 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The IBM Watson™ Visual Recognition service uses deep learning algorithms to identify scenes, objects, and faces in images you upload to the service. You can create and train a custom classifier to identify subjects that suit your needs. """ from __future__ import absolute_import import json from .watson_service import datetime_to_string, string_to_datetime from os.path import basename import re from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class VisualRecognitionV3(WatsonService): """The Visual Recognition V3 service.""" default_url = 'https://gateway.watsonplatform.net/visual-recognition/api' def __init__( self, version, url=default_url, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Visual Recognition service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/visual-recognition/api"). The base url may differ between Bluemix regions. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='watson_vision_combined', url=url, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Visual Recognition') self.version = version ######################### # General ######################### def classify(self, images_file=None, accept_language=None, url=None, threshold=None, owners=None, classifier_ids=None, images_file_content_type=None, images_filename=None, **kwargs): """ Classify images. Classify images with built-in or custom classifiers. :param file images_file: An image file (.gif, .jpg, .png, .tif) or .zip file with images. Maximum image size is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. :param str accept_language: The desired language of parts of the response. See the response for details. :param str url: The URL of an image (.gif, .jpg, .png, .tif) to analyze. The minimum recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 pixels. The maximum image size is 10 MB. You can also include images with the **images_file** parameter. :param float threshold: The minimum score a class must have to be displayed in the response. Set the threshold to `0.0` to return all identified classes. :param list[str] owners: The categories of classifiers to apply. The **classifier_ids** parameter overrides **owners**, so make sure that **classifier_ids** is empty. - Use `IBM` to classify against the `default` general classifier. You get the same result if both **classifier_ids** and **owners** parameters are empty. - Use `me` to classify against all your custom classifiers. However, for better performance use **classifier_ids** to specify the specific custom classifiers to apply. - Use both `IBM` and `me` to analyze the image against both classifier categories. :param list[str] classifier_ids: Which classifiers to apply. Overrides the **owners** parameter. You can specify both custom and built-in classifier IDs. The built-in `default` classifier is used if both **classifier_ids** and **owners** parameters are empty. The following built-in classifier IDs require no training: - `default`: Returns classes from thousands of general tags. - `food`: Enhances specificity and accuracy for images of food items. - `explicit`: Evaluates whether the image might be pornographic. :param str images_file_content_type: The content type of images_file. :param str images_filename: The filename for images_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ headers = {'Accept-Language': accept_language} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=classify' params = {'version': self.version} form_data = {} if images_file: if not images_filename and hasattr(images_file, 'name'): images_filename = basename(images_file.name) form_data['images_file'] = (images_filename, images_file, images_file_content_type or 'application/octet-stream') if url: form_data['url'] = (None, url, 'text/plain') if threshold: form_data['threshold'] = (None, threshold, 'application/json') if owners: owners = self._convert_list(owners) form_data['owners'] = (None, owners, 'application/json') if classifier_ids: classifier_ids = self._convert_list(classifier_ids) form_data['classifier_ids'] = (None, classifier_ids, 'application/json') url = '/v3/classify' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Face ######################### def detect_faces(self, images_file=None, url=None, images_file_content_type=None, images_filename=None, accept_language=None, **kwargs): """ Detect faces in images. **Important:** On April 2, 2018, the identity information in the response to calls to the Face model was removed. The identity information refers to the `name` of the person, `score`, and `type_hierarchy` knowledge graph. For details about the enhanced Face model, see the [Release notes](https://cloud.ibm.com/docs/services/visual-recognition/release-notes.html#2april2018). Analyze and get data about faces in images. Responses can include estimated age and gender. This feature uses a built-in model, so no training is necessary. The Detect faces method does not support general biometric facial recognition. Supported image formats include .gif, .jpg, .png, and .tif. The maximum image size is 10 MB. The minimum recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 pixels. :param file images_file: An image file (gif, .jpg, .png, .tif.) or .zip file with images. Limit the .zip file to 100 MB. You can include a maximum of 15 images in a request. Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. :param str url: The URL of an image to analyze. Must be in .gif, .jpg, .png, or .tif format. The minimum recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 pixels. The maximum image size is 10 MB. Redirects are followed, so you can use a shortened URL. You can also include images with the **images_file** parameter. :param str images_file_content_type: The content type of images_file. :param str images_filename: The filename for images_file. :param str accept_language: The desired language of parts of the response. See the response for details. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ headers = {'Accept-Language': accept_language} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=detect_faces' params = {'version': self.version} form_data = {} if images_file: if not images_filename and hasattr(images_file, 'name'): images_filename = basename(images_file.name) form_data['images_file'] = (images_filename, images_file, images_file_content_type or 'application/octet-stream') if url: form_data['url'] = (None, url, 'text/plain') url = '/v3/detect_faces' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Custom ######################### def create_classifier(self, name, negative_examples=None, negative_examples_filename=None, **kwargs): """ Create a classifier. Train a new multi-faceted classifier on the uploaded image data. Create your custom classifier with positive or negative examples. Include at least two sets of examples, either two positive example files or one positive and one negative file. You can upload a maximum of 256 MB per call. Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. :param str name: The name of the new classifier. Encode special characters in UTF-8. :param file negative_examples: A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. :param str negative_examples_filename: The filename for negative_examples. :param file positive_examples: A .zip file of images that depict the visual subject of a class in the new classifier. You can include more than one positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, `goldenretriever_positive_examples` creates the class **goldenretriever**. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. :param str positive_examples_filename: The filename for positive_examples. :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') positive_examples_keys = [ key for key in kwargs if re.match('^.+_positive_examples$', key) ] if not positive_examples_keys: raise ValueError( 'At least one _positive_examples parameter must be provided' ) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=create_classifier' params = {'version': self.version} form_data = {} form_data['name'] = (None, name, 'text/plain') if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): negative_examples_filename = basename(negative_examples.name) if not negative_examples_filename: raise ValueError('negative_examples_filename must be provided') form_data['negative_examples'] = (negative_examples_filename, negative_examples, 'application/octet-stream') for key in positive_examples_keys: value = kwargs[key] filename = kwargs.get(key + '_filename') if not filename and hasattr(value, 'name'): filename = basename(value.name) form_data[key] = (filename, value, 'application/octet-stream') url = '/v3/classifiers' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response def delete_classifier(self, classifier_id, **kwargs): """ Delete a classifier. :param str classifier_id: The ID of the classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=delete_classifier' params = {'version': self.version} url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_classifier(self, classifier_id, **kwargs): """ Retrieve classifier details. Retrieve information about a custom classifier. :param str classifier_id: The ID of the classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=get_classifier' params = {'version': self.version} url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_classifiers(self, verbose=None, **kwargs): """ Retrieve a list of classifiers. :param bool verbose: Specify `true` to return details about the classifiers. Omit this parameter to return a brief list of classifiers. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=list_classifiers' params = {'version': self.version, 'verbose': verbose} url = '/v3/classifiers' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_classifier(self, classifier_id, negative_examples=None, negative_examples_filename=None, **kwargs): """ Update a classifier. Update a custom classifier by adding new positive or negative classes or by adding new images to existing classes. You must supply at least one set of positive or negative examples. For details, see [Updating custom classifiers](https://cloud.ibm.com/docs/services/visual-recognition/customizing.html#updating-custom-classifiers). Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. **Tip:** Don't make retraining calls on a classifier until the status is ready. When you submit retraining requests in parallel, the last request overwrites the previous requests. The retrained property shows the last time the classifier retraining finished. :param str classifier_id: The ID of the classifier. :param file negative_examples: A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. :param str negative_examples_filename: The filename for negative_examples. :param file positive_examples: A .zip file of images that depict the visual subject of a class in the classifier. The positive examples create or update classes in the classifier. You can include more than one positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, `goldenretriever_positive_examples` creates the class `goldenretriever`. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. :param str positive_examples_filename: The filename for positive_examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') positive_examples_keys = [ key for key in kwargs if re.match('^.+_positive_examples$', key) ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=update_classifier' params = {'version': self.version} form_data = {} if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): negative_examples_filename = basename(negative_examples.name) if not negative_examples_filename: raise ValueError('negative_examples_filename must be provided') form_data['negative_examples'] = (negative_examples_filename, negative_examples, 'application/octet-stream') for key in positive_examples_keys: value = kwargs[key] filename = kwargs.get(key + '_filename') if not filename and hasattr(value, 'name'): filename = basename(value.name) form_data[key] = (filename, value, 'application/octet-stream') url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Core ML ######################### def get_core_ml_model(self, classifier_id, **kwargs): """ Retrieve a Core ML model of a classifier. Download a Core ML model file (.mlmodel) of a custom classifier that returns \"core_ml_enabled\": true in the classifier details. :param str classifier_id: The ID of the classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=get_core_ml_model' params = {'version': self.version} url = '/v3/classifiers/{0}/core_ml_model'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=False) return response ######################### # User data ######################### def delete_user_data(self, customer_id, **kwargs): """ Delete labeled data. Deletes all data associated with a specified customer ID. The method has no effect if no data is associated with the customer ID. You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes data. For more information about personal data and customer IDs, see [Information security](https://cloud.ibm.com/docs/services/visual-recognition/information-security.html). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=watson_vision_combined;service_version=V3;operation_id=delete_user_data' params = {'version': self.version, 'customer_id': customer_id} url = '/v3/user_data' response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class Class(object): """ A category within a classifier. :attr str class_name: The name of the class. """ def __init__(self, class_name): """ Initialize a Class object. :param str class_name: The name of the class. """ self.class_name = class_name @classmethod def _from_dict(cls, _dict): """Initialize a Class object from a json dictionary.""" args = {} if 'class' in _dict or 'class_name' in _dict: args['class_name'] = _dict.get('class') or _dict.get('class_name') else: raise ValueError( 'Required property \'class\' not present in Class JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'class_name') and self.class_name is not None: _dict['class'] = self.class_name return _dict def __str__(self): """Return a `str` version of this Class object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassResult(object): """ Result of a class within a classifier. :attr str class_name: Name of the class. Class names are translated in the language defined by the **Accept-Language** request header for the build-in classifier IDs (`default`, `food`, and `explicit`). Class names of custom classifiers are not translated. The response might not be in the specified language when the requested language is not supported or when there is no translation for the class name. :attr float score: Confidence score for the property in the range of 0 to 1. A higher score indicates greater likelihood that the class is depicted in the image. The default threshold for returning scores from a classifier is 0.5. :attr str type_hierarchy: (optional) Knowledge graph of the property. For example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if identified. """ def __init__(self, class_name, score, type_hierarchy=None): """ Initialize a ClassResult object. :param str class_name: Name of the class. Class names are translated in the language defined by the **Accept-Language** request header for the build-in classifier IDs (`default`, `food`, and `explicit`). Class names of custom classifiers are not translated. The response might not be in the specified language when the requested language is not supported or when there is no translation for the class name. :param float score: Confidence score for the property in the range of 0 to 1. A higher score indicates greater likelihood that the class is depicted in the image. The default threshold for returning scores from a classifier is 0.5. :param str type_hierarchy: (optional) Knowledge graph of the property. For example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if identified. """ self.class_name = class_name self.score = score self.type_hierarchy = type_hierarchy @classmethod def _from_dict(cls, _dict): """Initialize a ClassResult object from a json dictionary.""" args = {} if 'class' in _dict or 'class_name' in _dict: args['class_name'] = _dict.get('class') or _dict.get('class_name') else: raise ValueError( 'Required property \'class\' not present in ClassResult JSON') if 'score' in _dict: args['score'] = _dict.get('score') else: raise ValueError( 'Required property \'score\' not present in ClassResult JSON') if 'type_hierarchy' in _dict: args['type_hierarchy'] = _dict.get('type_hierarchy') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'class_name') and self.class_name is not None: _dict['class'] = self.class_name if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'type_hierarchy') and self.type_hierarchy is not None: _dict['type_hierarchy'] = self.type_hierarchy return _dict def __str__(self): """Return a `str` version of this ClassResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassifiedImage(object): """ Results for one image. :attr str source_url: (optional) Source of the image before any redirects. Not returned when the image is uploaded. :attr str resolved_url: (optional) Fully resolved URL of the image after redirects are followed. Not returned when the image is uploaded. :attr str image: (optional) Relative path of the image file if uploaded directly. Not returned when the image is passed by URL. :attr ErrorInfo error: (optional) Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. :attr list[ClassifierResult] classifiers: The classifiers. """ def __init__(self, classifiers, source_url=None, resolved_url=None, image=None, error=None): """ Initialize a ClassifiedImage object. :param list[ClassifierResult] classifiers: The classifiers. :param str source_url: (optional) Source of the image before any redirects. Not returned when the image is uploaded. :param str resolved_url: (optional) Fully resolved URL of the image after redirects are followed. Not returned when the image is uploaded. :param str image: (optional) Relative path of the image file if uploaded directly. Not returned when the image is passed by URL. :param ErrorInfo error: (optional) Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. """ self.source_url = source_url self.resolved_url = resolved_url self.image = image self.error = error self.classifiers = classifiers @classmethod def _from_dict(cls, _dict): """Initialize a ClassifiedImage object from a json dictionary.""" args = {} if 'source_url' in _dict: args['source_url'] = _dict.get('source_url') if 'resolved_url' in _dict: args['resolved_url'] = _dict.get('resolved_url') if 'image' in _dict: args['image'] = _dict.get('image') if 'error' in _dict: args['error'] = ErrorInfo._from_dict(_dict.get('error')) if 'classifiers' in _dict: args['classifiers'] = [ ClassifierResult._from_dict(x) for x in (_dict.get('classifiers')) ] else: raise ValueError( 'Required property \'classifiers\' not present in ClassifiedImage JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'source_url') and self.source_url is not None: _dict['source_url'] = self.source_url if hasattr(self, 'resolved_url') and self.resolved_url is not None: _dict['resolved_url'] = self.resolved_url if hasattr(self, 'image') and self.image is not None: _dict['image'] = self.image if hasattr(self, 'error') and self.error is not None: _dict['error'] = self.error._to_dict() if hasattr(self, 'classifiers') and self.classifiers is not None: _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict def __str__(self): """Return a `str` version of this ClassifiedImage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassifiedImages(object): """ Results for all images. :attr int custom_classes: (optional) Number of custom classes identified in the images. :attr int images_processed: (optional) Number of images processed for the API call. :attr list[ClassifiedImage] images: Classified images. :attr list[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. """ def __init__(self, images, custom_classes=None, images_processed=None, warnings=None): """ Initialize a ClassifiedImages object. :param list[ClassifiedImage] images: Classified images. :param int custom_classes: (optional) Number of custom classes identified in the images. :param int images_processed: (optional) Number of images processed for the API call. :param list[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. """ self.custom_classes = custom_classes self.images_processed = images_processed self.images = images self.warnings = warnings @classmethod def _from_dict(cls, _dict): """Initialize a ClassifiedImages object from a json dictionary.""" args = {} if 'custom_classes' in _dict: args['custom_classes'] = _dict.get('custom_classes') if 'images_processed' in _dict: args['images_processed'] = _dict.get('images_processed') if 'images' in _dict: args['images'] = [ ClassifiedImage._from_dict(x) for x in (_dict.get('images')) ] else: raise ValueError( 'Required property \'images\' not present in ClassifiedImages JSON' ) if 'warnings' in _dict: args['warnings'] = [ WarningInfo._from_dict(x) for x in (_dict.get('warnings')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'custom_classes') and self.custom_classes is not None: _dict['custom_classes'] = self.custom_classes if hasattr(self, 'images_processed') and self.images_processed is not None: _dict['images_processed'] = self.images_processed if hasattr(self, 'images') and self.images is not None: _dict['images'] = [x._to_dict() for x in self.images] if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict def __str__(self): """Return a `str` version of this ClassifiedImages object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Classifier(object): """ Information about a classifier. :attr str classifier_id: ID of a classifier identified in the image. :attr str name: Name of the classifier. :attr str owner: (optional) Unique ID of the account who owns the classifier. Might not be returned by some requests. :attr str status: (optional) Training status of classifier. :attr bool core_ml_enabled: (optional) Whether the classifier can be downloaded as a Core ML model after the training status is `ready`. :attr str explanation: (optional) If classifier training has failed, this field might explain why. :attr datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was created. :attr list[Class] classes: (optional) Classes that define a classifier. :attr datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Might not be returned by some requests. Identical to `updated` and retained for backward compatibility. :attr datetime updated: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was most recently updated. The field matches either `retrained` or `created`. Might not be returned by some requests. """ def __init__(self, classifier_id, name, owner=None, status=None, core_ml_enabled=None, explanation=None, created=None, classes=None, retrained=None, updated=None): """ Initialize a Classifier object. :param str classifier_id: ID of a classifier identified in the image. :param str name: Name of the classifier. :param str owner: (optional) Unique ID of the account who owns the classifier. Might not be returned by some requests. :param str status: (optional) Training status of classifier. :param bool core_ml_enabled: (optional) Whether the classifier can be downloaded as a Core ML model after the training status is `ready`. :param str explanation: (optional) If classifier training has failed, this field might explain why. :param datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was created. :param list[Class] classes: (optional) Classes that define a classifier. :param datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Might not be returned by some requests. Identical to `updated` and retained for backward compatibility. :param datetime updated: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was most recently updated. The field matches either `retrained` or `created`. Might not be returned by some requests. """ self.classifier_id = classifier_id self.name = name self.owner = owner self.status = status self.core_ml_enabled = core_ml_enabled self.explanation = explanation self.created = created self.classes = classes self.retrained = retrained self.updated = updated @classmethod def _from_dict(cls, _dict): """Initialize a Classifier object from a json dictionary.""" args = {} if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') else: raise ValueError( 'Required property \'classifier_id\' not present in Classifier JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Classifier JSON') if 'owner' in _dict: args['owner'] = _dict.get('owner') if 'status' in _dict: args['status'] = _dict.get('status') if 'core_ml_enabled' in _dict: args['core_ml_enabled'] = _dict.get('core_ml_enabled') if 'explanation' in _dict: args['explanation'] = _dict.get('explanation') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'classes' in _dict: args['classes'] = [ Class._from_dict(x) for x in (_dict.get('classes')) ] if 'retrained' in _dict: args['retrained'] = string_to_datetime(_dict.get('retrained')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifier_id') and self.classifier_id is not None: _dict['classifier_id'] = self.classifier_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'owner') and self.owner is not None: _dict['owner'] = self.owner if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'core_ml_enabled') and self.core_ml_enabled is not None: _dict['core_ml_enabled'] = self.core_ml_enabled if hasattr(self, 'explanation') and self.explanation is not None: _dict['explanation'] = self.explanation if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'classes') and self.classes is not None: _dict['classes'] = [x._to_dict() for x in self.classes] if hasattr(self, 'retrained') and self.retrained is not None: _dict['retrained'] = datetime_to_string(self.retrained) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) return _dict def __str__(self): """Return a `str` version of this Classifier object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassifierResult(object): """ Classifier and score combination. :attr str name: Name of the classifier. :attr str classifier_id: ID of a classifier identified in the image. :attr list[ClassResult] classes: Classes within the classifier. """ def __init__(self, name, classifier_id, classes): """ Initialize a ClassifierResult object. :param str name: Name of the classifier. :param str classifier_id: ID of a classifier identified in the image. :param list[ClassResult] classes: Classes within the classifier. """ self.name = name self.classifier_id = classifier_id self.classes = classes @classmethod def _from_dict(cls, _dict): """Initialize a ClassifierResult object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in ClassifierResult JSON' ) if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') else: raise ValueError( 'Required property \'classifier_id\' not present in ClassifierResult JSON' ) if 'classes' in _dict: args['classes'] = [ ClassResult._from_dict(x) for x in (_dict.get('classes')) ] else: raise ValueError( 'Required property \'classes\' not present in ClassifierResult JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'classifier_id') and self.classifier_id is not None: _dict['classifier_id'] = self.classifier_id if hasattr(self, 'classes') and self.classes is not None: _dict['classes'] = [x._to_dict() for x in self.classes] return _dict def __str__(self): """Return a `str` version of this ClassifierResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Classifiers(object): """ A container for the list of classifiers. :attr list[Classifier] classifiers: List of classifiers. """ def __init__(self, classifiers): """ Initialize a Classifiers object. :param list[Classifier] classifiers: List of classifiers. """ self.classifiers = classifiers @classmethod def _from_dict(cls, _dict): """Initialize a Classifiers object from a json dictionary.""" args = {} if 'classifiers' in _dict: args['classifiers'] = [ Classifier._from_dict(x) for x in (_dict.get('classifiers')) ] else: raise ValueError( 'Required property \'classifiers\' not present in Classifiers JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifiers') and self.classifiers is not None: _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict def __str__(self): """Return a `str` version of this Classifiers object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DetectedFaces(object): """ Results for all faces. :attr int images_processed: Number of images processed for the API call. :attr list[ImageWithFaces] images: The images. :attr list[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. """ def __init__(self, images_processed, images, warnings=None): """ Initialize a DetectedFaces object. :param int images_processed: Number of images processed for the API call. :param list[ImageWithFaces] images: The images. :param list[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. """ self.images_processed = images_processed self.images = images self.warnings = warnings @classmethod def _from_dict(cls, _dict): """Initialize a DetectedFaces object from a json dictionary.""" args = {} if 'images_processed' in _dict: args['images_processed'] = _dict.get('images_processed') else: raise ValueError( 'Required property \'images_processed\' not present in DetectedFaces JSON' ) if 'images' in _dict: args['images'] = [ ImageWithFaces._from_dict(x) for x in (_dict.get('images')) ] else: raise ValueError( 'Required property \'images\' not present in DetectedFaces JSON' ) if 'warnings' in _dict: args['warnings'] = [ WarningInfo._from_dict(x) for x in (_dict.get('warnings')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'images_processed') and self.images_processed is not None: _dict['images_processed'] = self.images_processed if hasattr(self, 'images') and self.images is not None: _dict['images'] = [x._to_dict() for x in self.images] if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict def __str__(self): """Return a `str` version of this DetectedFaces object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ErrorInfo(object): """ Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. :attr int code: HTTP status code. :attr str description: Human-readable error description. For example, `File size limit exceeded`. :attr str error_id: Codified error string. For example, `limit_exceeded`. """ def __init__(self, code, description, error_id): """ Initialize a ErrorInfo object. :param int code: HTTP status code. :param str description: Human-readable error description. For example, `File size limit exceeded`. :param str error_id: Codified error string. For example, `limit_exceeded`. """ self.code = code self.description = description self.error_id = error_id @classmethod def _from_dict(cls, _dict): """Initialize a ErrorInfo object from a json dictionary.""" args = {} if 'code' in _dict: args['code'] = _dict.get('code') else: raise ValueError( 'Required property \'code\' not present in ErrorInfo JSON') if 'description' in _dict: args['description'] = _dict.get('description') else: raise ValueError( 'Required property \'description\' not present in ErrorInfo JSON' ) if 'error_id' in _dict: args['error_id'] = _dict.get('error_id') else: raise ValueError( 'Required property \'error_id\' not present in ErrorInfo JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'error_id') and self.error_id is not None: _dict['error_id'] = self.error_id return _dict def __str__(self): """Return a `str` version of this ErrorInfo object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Face(object): """ Information about the face. :attr FaceAge age: (optional) Age information about a face. :attr FaceGender gender: (optional) Information about the gender of the face. :attr FaceLocation face_location: (optional) The location of the bounding box around the face. """ def __init__(self, age=None, gender=None, face_location=None): """ Initialize a Face object. :param FaceAge age: (optional) Age information about a face. :param FaceGender gender: (optional) Information about the gender of the face. :param FaceLocation face_location: (optional) The location of the bounding box around the face. """ self.age = age self.gender = gender self.face_location = face_location @classmethod def _from_dict(cls, _dict): """Initialize a Face object from a json dictionary.""" args = {} if 'age' in _dict: args['age'] = FaceAge._from_dict(_dict.get('age')) if 'gender' in _dict: args['gender'] = FaceGender._from_dict(_dict.get('gender')) if 'face_location' in _dict: args['face_location'] = FaceLocation._from_dict( _dict.get('face_location')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'age') and self.age is not None: _dict['age'] = self.age._to_dict() if hasattr(self, 'gender') and self.gender is not None: _dict['gender'] = self.gender._to_dict() if hasattr(self, 'face_location') and self.face_location is not None: _dict['face_location'] = self.face_location._to_dict() return _dict def __str__(self): """Return a `str` version of this Face object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FaceAge(object): """ Age information about a face. :attr int min: (optional) Estimated minimum age. :attr int max: (optional) Estimated maximum age. :attr float score: Confidence score in the range of 0 to 1. A higher score indicates greater confidence in the estimated value for the property. """ def __init__(self, score, min=None, max=None): """ Initialize a FaceAge object. :param float score: Confidence score in the range of 0 to 1. A higher score indicates greater confidence in the estimated value for the property. :param int min: (optional) Estimated minimum age. :param int max: (optional) Estimated maximum age. """ self.min = min self.max = max self.score = score @classmethod def _from_dict(cls, _dict): """Initialize a FaceAge object from a json dictionary.""" args = {} if 'min' in _dict: args['min'] = _dict.get('min') if 'max' in _dict: args['max'] = _dict.get('max') if 'score' in _dict: args['score'] = _dict.get('score') else: raise ValueError( 'Required property \'score\' not present in FaceAge JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'min') and self.min is not None: _dict['min'] = self.min if hasattr(self, 'max') and self.max is not None: _dict['max'] = self.max if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict def __str__(self): """Return a `str` version of this FaceAge object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FaceGender(object): """ Information about the gender of the face. :attr str gender: Gender identified by the face. For example, `MALE` or `FEMALE`. :attr str gender_label: The word for "male" or "female" in the language defined by the **Accept-Language** request header. :attr float score: Confidence score in the range of 0 to 1. A higher score indicates greater confidence in the estimated value for the property. """ def __init__(self, gender, gender_label, score): """ Initialize a FaceGender object. :param str gender: Gender identified by the face. For example, `MALE` or `FEMALE`. :param str gender_label: The word for "male" or "female" in the language defined by the **Accept-Language** request header. :param float score: Confidence score in the range of 0 to 1. A higher score indicates greater confidence in the estimated value for the property. """ self.gender = gender self.gender_label = gender_label self.score = score @classmethod def _from_dict(cls, _dict): """Initialize a FaceGender object from a json dictionary.""" args = {} if 'gender' in _dict: args['gender'] = _dict.get('gender') else: raise ValueError( 'Required property \'gender\' not present in FaceGender JSON') if 'gender_label' in _dict: args['gender_label'] = _dict.get('gender_label') else: raise ValueError( 'Required property \'gender_label\' not present in FaceGender JSON' ) if 'score' in _dict: args['score'] = _dict.get('score') else: raise ValueError( 'Required property \'score\' not present in FaceGender JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'gender') and self.gender is not None: _dict['gender'] = self.gender if hasattr(self, 'gender_label') and self.gender_label is not None: _dict['gender_label'] = self.gender_label if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict def __str__(self): """Return a `str` version of this FaceGender object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FaceLocation(object): """ The location of the bounding box around the face. :attr float width: Width in pixels of face region. :attr float height: Height in pixels of face region. :attr float left: X-position of top-left pixel of face region. :attr float top: Y-position of top-left pixel of face region. """ def __init__(self, width, height, left, top): """ Initialize a FaceLocation object. :param float width: Width in pixels of face region. :param float height: Height in pixels of face region. :param float left: X-position of top-left pixel of face region. :param float top: Y-position of top-left pixel of face region. """ self.width = width self.height = height self.left = left self.top = top @classmethod def _from_dict(cls, _dict): """Initialize a FaceLocation object from a json dictionary.""" args = {} if 'width' in _dict: args['width'] = _dict.get('width') else: raise ValueError( 'Required property \'width\' not present in FaceLocation JSON') if 'height' in _dict: args['height'] = _dict.get('height') else: raise ValueError( 'Required property \'height\' not present in FaceLocation JSON') if 'left' in _dict: args['left'] = _dict.get('left') else: raise ValueError( 'Required property \'left\' not present in FaceLocation JSON') if 'top' in _dict: args['top'] = _dict.get('top') else: raise ValueError( 'Required property \'top\' not present in FaceLocation JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'width') and self.width is not None: _dict['width'] = self.width if hasattr(self, 'height') and self.height is not None: _dict['height'] = self.height if hasattr(self, 'left') and self.left is not None: _dict['left'] = self.left if hasattr(self, 'top') and self.top is not None: _dict['top'] = self.top return _dict def __str__(self): """Return a `str` version of this FaceLocation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ImageWithFaces(object): """ Information about faces in the image. :attr list[Face] faces: Faces detected in the images. :attr str image: (optional) Relative path of the image file if uploaded directly. Not returned when the image is passed by URL. :attr str source_url: (optional) Source of the image before any redirects. Not returned when the image is uploaded. :attr str resolved_url: (optional) Fully resolved URL of the image after redirects are followed. Not returned when the image is uploaded. :attr ErrorInfo error: (optional) Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. """ def __init__(self, faces, image=None, source_url=None, resolved_url=None, error=None): """ Initialize a ImageWithFaces object. :param list[Face] faces: Faces detected in the images. :param str image: (optional) Relative path of the image file if uploaded directly. Not returned when the image is passed by URL. :param str source_url: (optional) Source of the image before any redirects. Not returned when the image is uploaded. :param str resolved_url: (optional) Fully resolved URL of the image after redirects are followed. Not returned when the image is uploaded. :param ErrorInfo error: (optional) Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. """ self.faces = faces self.image = image self.source_url = source_url self.resolved_url = resolved_url self.error = error @classmethod def _from_dict(cls, _dict): """Initialize a ImageWithFaces object from a json dictionary.""" args = {} if 'faces' in _dict: args['faces'] = [Face._from_dict(x) for x in (_dict.get('faces'))] else: raise ValueError( 'Required property \'faces\' not present in ImageWithFaces JSON' ) if 'image' in _dict: args['image'] = _dict.get('image') if 'source_url' in _dict: args['source_url'] = _dict.get('source_url') if 'resolved_url' in _dict: args['resolved_url'] = _dict.get('resolved_url') if 'error' in _dict: args['error'] = ErrorInfo._from_dict(_dict.get('error')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'faces') and self.faces is not None: _dict['faces'] = [x._to_dict() for x in self.faces] if hasattr(self, 'image') and self.image is not None: _dict['image'] = self.image if hasattr(self, 'source_url') and self.source_url is not None: _dict['source_url'] = self.source_url if hasattr(self, 'resolved_url') and self.resolved_url is not None: _dict['resolved_url'] = self.resolved_url if hasattr(self, 'error') and self.error is not None: _dict['error'] = self.error._to_dict() return _dict def __str__(self): """Return a `str` version of this ImageWithFaces object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WarningInfo(object): """ Information about something that went wrong. :attr str warning_id: Codified warning string, such as `limit_reached`. :attr str description: Information about the error. """ def __init__(self, warning_id, description): """ Initialize a WarningInfo object. :param str warning_id: Codified warning string, such as `limit_reached`. :param str description: Information about the error. """ self.warning_id = warning_id self.description = description @classmethod def _from_dict(cls, _dict): """Initialize a WarningInfo object from a json dictionary.""" args = {} if 'warning_id' in _dict: args['warning_id'] = _dict.get('warning_id') else: raise ValueError( 'Required property \'warning_id\' not present in WarningInfo JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') else: raise ValueError( 'Required property \'description\' not present in WarningInfo JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'warning_id') and self.warning_id is not None: _dict['warning_id'] = self.warning_id if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict def __str__(self): """Return a `str` version of this WarningInfo object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/speech_to_text_v1.py0000644000076500000240000103362613451407070030420 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The 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. 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 audio to the service and receive results over a single connection asynchronously. The service also offers two customization interfaces. Use language model customization to expand the vocabulary of a base model with domain-specific terminology. Use acoustic model customization to adapt a base model for the acoustic characteristics of your audio. For language model customization, the service also supports grammars. A grammar is a formal language specification that lets you restrict the phrases that the service can recognize. Language model customization is generally available for production use with most supported languages. Acoustic model customization is beta functionality that is available for all supported languages. """ from __future__ import absolute_import import json from os.path import basename from .watson_service import WatsonService ############################################################################## # Service ############################################################################## class SpeechToTextV1(WatsonService): """The Speech to Text V1 service.""" default_url = 'https://stream.watsonplatform.net/speech-to-text/api' def __init__( self, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Speech to Text service. :param str url: The base url to use when contacting the service (e.g. "https://stream.watsonplatform.net/speech-to-text/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='speech_to_text', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Speech to Text') ######################### # Models ######################### def get_model(self, model_id, **kwargs): """ Get a model. Gets information for a single specified language model that is available for use with the service. The information includes the name of the model and its minimum sampling rate in Hertz, among other things. **See also:** [Languages and models](https://cloud.ibm.com/docs/services/speech-to-text/models.html). :param str model_id: The identifier of the model in the form of its name from the output of the **Get a model** method. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if model_id is None: raise ValueError('model_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=get_model' url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_models(self, **kwargs): """ List models. 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. **See also:** [Languages and models](https://cloud.ibm.com/docs/services/speech-to-text/models.html). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=list_models' url = '/v1/models' response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response ######################### # Synchronous ######################### def recognize(self, audio, content_type=None, model=None, language_customization_id=None, acoustic_customization_id=None, base_model_version=None, customization_weight=None, inactivity_timeout=None, keywords=None, keywords_threshold=None, max_alternatives=None, word_alternatives_threshold=None, word_confidence=None, timestamps=None, profanity_filter=None, smart_formatting=None, speaker_labels=None, customization_id=None, grammar_name=None, redaction=None, **kwargs): """ Recognize audio. Sends audio and returns transcription results for a recognition request. You can pass a maximum of 100 MB and a minimum of 100 bytes of audio with a request. The service automatically detects the endianness of the incoming audio and, for audio that includes multiple channels, downmixes the audio to one-channel mono during transcoding. The method returns only final results; to enable interim results, use the WebSocket API. **See also:** [Making a basic HTTP request](https://cloud.ibm.com/docs/services/speech-to-text/http.html#HTTP-basic). ### Streaming mode For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to `chunked` to use streaming mode. In streaming mode, the server closes the connection (status code 408) if the service receives no data chunk for 30 seconds and it has no audio to transcribe for 30 seconds. The server also closes the connection (status code 400) if no speech is detected for `inactivity_timeout` seconds of audio (not processing time); use the `inactivity_timeout` parameter to change the default of 30 seconds. **See also:** * [Audio transmission](https://cloud.ibm.com/docs/services/speech-to-text/input.html#transmission) * [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts) ### Audio formats (content types) The service accepts audio in the following formats (MIME types). * For formats that are labeled **Required**, you must use the `Content-Type` header with the request to specify the format of the audio. * For all other formats, you can omit the `Content-Type` header or specify `application/octet-stream` with the header to have the service automatically detect the format of the audio. (With the `curl` command, you can specify either `\"Content-Type:\"` or `\"Content-Type: application/octet-stream\"`.) Where indicated, the format that you specify must include the sampling rate and can optionally include the number of channels and the endianness of the audio. * `audio/basic` (**Required.** Use only with narrowband models.) * `audio/flac` * `audio/g729` (Use only with narrowband models.) * `audio/l16` (**Required.** Specify the sampling rate (`rate`) and optionally the number of channels (`channels`) and endianness (`endianness`) of the audio.) * `audio/mp3` * `audio/mpeg` * `audio/mulaw` (**Required.** Specify the sampling rate (`rate`) of the audio.) * `audio/ogg` (The service automatically detects the codec of the input audio.) * `audio/ogg;codecs=opus` * `audio/ogg;codecs=vorbis` * `audio/wav` (Provide audio with a maximum of nine channels.) * `audio/webm` (The service automatically detects the codec of the input audio.) * `audio/webm;codecs=opus` * `audio/webm;codecs=vorbis` The sampling rate of the audio must match the sampling rate of the model for the recognition request: for broadband models, at least 16 kHz; for narrowband models, at least 8 kHz. If the sampling rate of the audio is higher than the minimum required rate, the service down-samples the audio to the appropriate rate. If the sampling rate of the audio is lower than the minimum required rate, the request fails. **See also:** [Audio formats](https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html). ### Multipart speech recognition **Note:** The Watson SDKs do not support multipart speech recognition. The HTTP `POST` method of the service also supports multipart speech recognition. With multipart requests, you pass all audio data as multipart form data. You specify some parameters as request headers and query parameters, but you pass JSON metadata as form data to control most aspects of the transcription. The multipart approach is intended for use with browsers for which JavaScript is disabled or when the parameters used with the request are greater than the 8 KB limit imposed by most HTTP servers and proxies. You can encounter this limit, for example, if you want to spot a very large number of keywords. **See also:** [Making a multipart HTTP request](https://cloud.ibm.com/docs/services/speech-to-text/http.html#HTTP-multi). :param file audio: The audio to transcribe. :param str content_type: The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. :param str model: The identifier of the model that is to be used for the recognition request. See [Languages and models](https://cloud.ibm.com/docs/services/speech-to-text/models.html). :param str language_customization_id: The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom language model is used. See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: The customization ID (GUID) of a custom acoustic model that is to be used with the recognition request. The base model of the specified custom acoustic model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom acoustic model is used. See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). :param str base_model_version: The version of the specified base model that is to be used with recognition request. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The default value depends on whether the parameter is used with or without a custom model. See [Base model version](https://cloud.ibm.com/docs/services/speech-to-text/input.html#version). :param float customization_weight: If you specify the customization ID (GUID) of a custom language model with the recognition request, the customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model when it was trained, the default value is 0.3. A customization weight that you specify overrides a weight that was specified when the custom model was trained. The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). :param int inactivity_timeout: The time in seconds after which, if only silence (no speech) is detected in submitted audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission from a live microphone when a user simply walks away. Use `-1` for infinity. See [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts). :param list[str] keywords: An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter or specify an empty array if you do not need to spot keywords. See [Keyword spotting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#keyword_spotting). :param float keywords_threshold: A confidence value that is the lower bound for spotting a keyword. A word is considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. If you specify a threshold, you must also specify one or more keywords. The service performs no keyword spotting if you omit either parameter. See [Keyword spotting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#keyword_spotting). :param int max_alternatives: The maximum number of alternative transcripts that the service is to return. By default, the service returns a single transcript. See [Maximum alternatives](https://cloud.ibm.com/docs/services/speech-to-text/output.html#max_alternatives). :param float word_alternatives_threshold: A confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as \"Confusion Networks\"). An alternative word is considered if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. By default, the service computes no alternative words. See [Word alternatives](https://cloud.ibm.com/docs/services/speech-to-text/output.html#word_alternatives). :param bool word_confidence: If `true`, the service returns a confidence measure in the range of 0.0 to 1.0 for each word. By default, the service returns no word confidence scores. See [Word confidence](https://cloud.ibm.com/docs/services/speech-to-text/output.html#word_confidence). :param bool timestamps: If `true`, the service returns time alignment for each word. By default, no timestamps are returned. See [Word timestamps](https://cloud.ibm.com/docs/services/speech-to-text/output.html#word_timestamps). :param bool profanity_filter: If `true`, the service filters profanity from all output except for keyword results by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US English transcription only. See [Profanity filtering](https://cloud.ibm.com/docs/services/speech-to-text/output.html#profanity_filter). :param bool smart_formatting: If `true`, the service converts dates, times, series of digits and numbers, phone numbers, currency values, and internet addresses into more readable, conventional representations in the final transcript of a recognition request. For US English, the service also converts certain keyword strings to punctuation symbols. By default, the service performs no smart formatting. **Note:** Applies to US English, Japanese, and Spanish transcription only. See [Smart formatting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#smart_formatting). :param bool speaker_labels: If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. **Note:** Applies to US English, Japanese, and Spanish transcription only. To determine whether a language model supports speaker labels, you can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker labels](https://cloud.ibm.com/docs/services/speech-to-text/output.html#speaker_labels). :param str customization_id: **Deprecated.** Use the `language_customization_id` parameter to specify the customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not specify both parameters with a request. :param str grammar_name: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified grammar; it does not recognize other custom words from the model's words resource. See [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/output.html). :param bool redaction: If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no redaction. When you enable redaction, the service automatically enables smart formatting, regardless of whether you explicitly disable that feature. To ensure maximum security, the service also disables keyword spotting (ignores the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the `max_alternatives` parameter to be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/services/speech-to-text/output.html#redaction). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if audio is None: raise ValueError('audio must be provided') headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=recognize' params = { 'model': model, 'language_customization_id': language_customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, 'customization_weight': customization_weight, 'inactivity_timeout': inactivity_timeout, 'keywords': self._convert_list(keywords), 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, 'word_alternatives_threshold': word_alternatives_threshold, 'word_confidence': word_confidence, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, 'speaker_labels': speaker_labels, 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction } data = audio url = '/v1/recognize' response = self.request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) return response ######################### # Asynchronous ######################### def check_job(self, id, **kwargs): """ Check a job. Returns information about the specified job. The response always includes the status of the job and its creation and update times. If the status is `completed`, the response includes the results of the recognition request. You must use credentials for the instance of the service that owns a job to list information about it. You can use the method to retrieve the results of any job, regardless of whether it was submitted with a callback URL and the `recognitions.completed_with_results` event, and you can retrieve the results multiple times for as long as they remain available. Use the **Check jobs** method to request information about the most recent jobs associated with the calling credentials. **See also:** [Checking the status and retrieving the results of a job](https://cloud.ibm.com/docs/services/speech-to-text/async.html#job). :param str id: The identifier of the asynchronous job that is to be used for the request. You must make the request with credentials for the instance of the service that owns the job. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if id is None: raise ValueError('id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=check_job' url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def check_jobs(self, **kwargs): """ Check jobs. Returns the ID and status of the latest 100 outstanding jobs associated with the credentials with which it is called. The method also returns the creation and update times of each job, and, if a job was created with a callback URL and a user token, the user token for the job. To obtain the results for a job whose status is `completed` or not one of the latest 100 outstanding jobs, use the **Check a job** method. A job and its results remain available until you delete them with the **Delete a job** method or until the job's time to live expires, whichever comes first. **See also:** [Checking the status of the latest jobs](https://cloud.ibm.com/docs/services/speech-to-text/async.html#jobs). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=check_jobs' url = '/v1/recognitions' response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def create_job(self, audio, content_type=None, model=None, callback_url=None, events=None, user_token=None, results_ttl=None, language_customization_id=None, acoustic_customization_id=None, base_model_version=None, customization_weight=None, inactivity_timeout=None, keywords=None, keywords_threshold=None, max_alternatives=None, word_alternatives_threshold=None, word_confidence=None, timestamps=None, profanity_filter=None, smart_formatting=None, speaker_labels=None, customization_id=None, grammar_name=None, redaction=None, **kwargs): """ Create a job. Creates a job for a new asynchronous recognition request. The job is owned by the instance of the service whose credentials are used to create it. How you learn the status and results of a job depends on the parameters you include with the job creation request: * By callback notification: Include the `callback_url` parameter to specify a URL to which the service is to send callback notifications when the status of the job changes. Optionally, you can also include the `events` and `user_token` parameters to subscribe to specific events and to specify a string that is to be included with each notification for the job. * By polling the service: Omit the `callback_url`, `events`, and `user_token` parameters. You must then use the **Check jobs** or **Check a job** methods to check the status of the job, using the latter to retrieve the results when the job is complete. The two approaches are not mutually exclusive. You can poll the service for job status or obtain results from the service manually even if you include a callback URL. In both cases, you can include the `results_ttl` parameter to specify how long the results are to remain available after the job is complete. Using the HTTPS **Check a job** method to retrieve results is more secure than receiving them via callback notification over HTTP because it provides confidentiality in addition to authentication and data integrity. The method supports the same basic parameters as other HTTP and WebSocket recognition requests. It also supports the following parameters specific to the asynchronous interface: * `callback_url` * `events` * `user_token` * `results_ttl` You can pass a maximum of 100 MB and a minimum of 100 bytes of audio with a request. The service automatically detects the endianness of the incoming audio and, for audio that includes multiple channels, downmixes the audio to one-channel mono during transcoding. The method returns only final results; to enable interim results, use the WebSocket API. **See also:** [Creating a job](https://cloud.ibm.com/docs/services/speech-to-text/async.html#create). ### Streaming mode For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to `chunked` to use streaming mode. In streaming mode, the server closes the connection (status code 408) if the service receives no data chunk for 30 seconds and it has no audio to transcribe for 30 seconds. The server also closes the connection (status code 400) if no speech is detected for `inactivity_timeout` seconds of audio (not processing time); use the `inactivity_timeout` parameter to change the default of 30 seconds. **See also:** * [Audio transmission](https://cloud.ibm.com/docs/services/speech-to-text/input.html#transmission) * [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts) ### Audio formats (content types) The service accepts audio in the following formats (MIME types). * For formats that are labeled **Required**, you must use the `Content-Type` header with the request to specify the format of the audio. * For all other formats, you can omit the `Content-Type` header or specify `application/octet-stream` with the header to have the service automatically detect the format of the audio. (With the `curl` command, you can specify either `\"Content-Type:\"` or `\"Content-Type: application/octet-stream\"`.) Where indicated, the format that you specify must include the sampling rate and can optionally include the number of channels and the endianness of the audio. * `audio/basic` (**Required.** Use only with narrowband models.) * `audio/flac` * `audio/g729` (Use only with narrowband models.) * `audio/l16` (**Required.** Specify the sampling rate (`rate`) and optionally the number of channels (`channels`) and endianness (`endianness`) of the audio.) * `audio/mp3` * `audio/mpeg` * `audio/mulaw` (**Required.** Specify the sampling rate (`rate`) of the audio.) * `audio/ogg` (The service automatically detects the codec of the input audio.) * `audio/ogg;codecs=opus` * `audio/ogg;codecs=vorbis` * `audio/wav` (Provide audio with a maximum of nine channels.) * `audio/webm` (The service automatically detects the codec of the input audio.) * `audio/webm;codecs=opus` * `audio/webm;codecs=vorbis` The sampling rate of the audio must match the sampling rate of the model for the recognition request: for broadband models, at least 16 kHz; for narrowband models, at least 8 kHz. If the sampling rate of the audio is higher than the minimum required rate, the service down-samples the audio to the appropriate rate. If the sampling rate of the audio is lower than the minimum required rate, the request fails. **See also:** [Audio formats](https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html). :param file audio: The audio to transcribe. :param str content_type: The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. :param str model: The identifier of the model that is to be used for the recognition request. See [Languages and models](https://cloud.ibm.com/docs/services/speech-to-text/models.html). :param str callback_url: A URL to which callback notifications are to be sent. The URL must already be successfully white-listed by using the **Register a callback** method. You can include the same callback URL with any number of job creation requests. Omit the parameter to poll the service for job completion and results. Use the `user_token` parameter to specify a unique user-specified string with each job to differentiate the callback notifications for the jobs. :param str events: If the job includes a callback URL, a comma-separated list of notification events to which to subscribe. Valid events are * `recognitions.started` generates a callback notification when the service begins to process the job. * `recognitions.completed` generates a callback notification when the job is complete. You must use the **Check a job** method to retrieve the results before they time out or are deleted. * `recognitions.completed_with_results` generates a callback notification when the job is complete. The notification includes the results of the request. * `recognitions.failed` generates a callback notification if the service experiences an error while processing the job. The `recognitions.completed` and `recognitions.completed_with_results` events are incompatible. You can specify only of the two events. If the job includes a callback URL, omit the parameter to subscribe to the default events: `recognitions.started`, `recognitions.completed`, and `recognitions.failed`. If the job does not include a callback URL, omit the parameter. :param str user_token: If the job includes a callback URL, a user-specified string that the service is to include with each callback notification for the job; the token allows the user to maintain an internal mapping between jobs and notification events. If the job does not include a callback URL, omit the parameter. :param int results_ttl: The number of minutes for which the results are to be available after the job has finished. If not delivered via a callback, the results must be retrieved within this time. Omit the parameter to use a time to live of one week. The parameter is valid with or without a callback URL. :param str language_customization_id: The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom language model is used. See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: The customization ID (GUID) of a custom acoustic model that is to be used with the recognition request. The base model of the specified custom acoustic model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom acoustic model is used. See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). :param str base_model_version: The version of the specified base model that is to be used with recognition request. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The default value depends on whether the parameter is used with or without a custom model. See [Base model version](https://cloud.ibm.com/docs/services/speech-to-text/input.html#version). :param float customization_weight: If you specify the customization ID (GUID) of a custom language model with the recognition request, the customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model when it was trained, the default value is 0.3. A customization weight that you specify overrides a weight that was specified when the custom model was trained. The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). :param int inactivity_timeout: The time in seconds after which, if only silence (no speech) is detected in submitted audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission from a live microphone when a user simply walks away. Use `-1` for infinity. See [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts). :param list[str] keywords: An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter or specify an empty array if you do not need to spot keywords. See [Keyword spotting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#keyword_spotting). :param float keywords_threshold: A confidence value that is the lower bound for spotting a keyword. A word is considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. If you specify a threshold, you must also specify one or more keywords. The service performs no keyword spotting if you omit either parameter. See [Keyword spotting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#keyword_spotting). :param int max_alternatives: The maximum number of alternative transcripts that the service is to return. By default, the service returns a single transcript. See [Maximum alternatives](https://cloud.ibm.com/docs/services/speech-to-text/output.html#max_alternatives). :param float word_alternatives_threshold: A confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as \"Confusion Networks\"). An alternative word is considered if its confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. By default, the service computes no alternative words. See [Word alternatives](https://cloud.ibm.com/docs/services/speech-to-text/output.html#word_alternatives). :param bool word_confidence: If `true`, the service returns a confidence measure in the range of 0.0 to 1.0 for each word. By default, the service returns no word confidence scores. See [Word confidence](https://cloud.ibm.com/docs/services/speech-to-text/output.html#word_confidence). :param bool timestamps: If `true`, the service returns time alignment for each word. By default, no timestamps are returned. See [Word timestamps](https://cloud.ibm.com/docs/services/speech-to-text/output.html#word_timestamps). :param bool profanity_filter: If `true`, the service filters profanity from all output except for keyword results by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US English transcription only. See [Profanity filtering](https://cloud.ibm.com/docs/services/speech-to-text/output.html#profanity_filter). :param bool smart_formatting: If `true`, the service converts dates, times, series of digits and numbers, phone numbers, currency values, and internet addresses into more readable, conventional representations in the final transcript of a recognition request. For US English, the service also converts certain keyword strings to punctuation symbols. By default, the service performs no smart formatting. **Note:** Applies to US English, Japanese, and Spanish transcription only. See [Smart formatting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#smart_formatting). :param bool speaker_labels: If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. **Note:** Applies to US English, Japanese, and Spanish transcription only. To determine whether a language model supports speaker labels, you can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker labels](https://cloud.ibm.com/docs/services/speech-to-text/output.html#speaker_labels). :param str customization_id: **Deprecated.** Use the `language_customization_id` parameter to specify the customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not specify both parameters with a request. :param str grammar_name: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified grammar; it does not recognize other custom words from the model's words resource. See [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/output.html). :param bool redaction: If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no redaction. When you enable redaction, the service automatically enables smart formatting, regardless of whether you explicitly disable that feature. To ensure maximum security, the service also disables keyword spotting (ignores the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the `max_alternatives` parameter to be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/services/speech-to-text/output.html#redaction). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if audio is None: raise ValueError('audio must be provided') headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=create_job' params = { 'model': model, 'callback_url': callback_url, 'events': events, 'user_token': user_token, 'results_ttl': results_ttl, 'language_customization_id': language_customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, 'customization_weight': customization_weight, 'inactivity_timeout': inactivity_timeout, 'keywords': self._convert_list(keywords), 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, 'word_alternatives_threshold': word_alternatives_threshold, 'word_confidence': word_confidence, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, 'speaker_labels': speaker_labels, 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction } data = audio url = '/v1/recognitions' response = self.request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) return response def delete_job(self, id, **kwargs): """ Delete a job. Deletes the specified job. You cannot delete a job that the service is actively processing. Once you delete a job, its results are no longer available. The service automatically deletes a job and its results when the time to live for the results expires. You must use credentials for the instance of the service that owns a job to delete it. **See also:** [Deleting a job](https://cloud.ibm.com/docs/services/speech-to-text/async.html#delete). :param str id: The identifier of the asynchronous job that is to be used for the request. You must make the request with credentials for the instance of the service that owns the job. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if id is None: raise ValueError('id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_job' url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def register_callback(self, callback_url, user_secret=None, **kwargs): """ 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 `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 from the service. The response must send status code 200 and must include the challenge string in its body. Set the `Content-Type` response header to `text/plain`. Upon receiving this response, the service responds to the original 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 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 service responds to the initial registration request with response code 200. If you specify a user secret with the request, the service uses it as a key to calculate an HMAC-SHA1 signature of the challenge string in its response to the `POST` request. It sends this signature in the `X-Callback-Signature` header of its `GET` request to the URL during registration. It also uses the secret to calculate a signature over the payload of every callback notification that uses the URL. The signature provides authentication and data integrity for HTTP communications. After you successfully register a callback URL, you can use it with an indefinite number of recognition requests. You can register a maximum of 20 callback URLS in a one-hour span of time. **See also:** [Registering a callback URL](https://cloud.ibm.com/docs/services/speech-to-text/async.html#register). :param str callback_url: An HTTP or HTTPS URL to which callback notifications are to be sent. To be white-listed, the URL must successfully echo the challenge string during URL verification. During verification, the client can also check the signature that the service sends in the `X-Callback-Signature` header to verify the origin of the request. :param str user_secret: A user-specified string that the service uses to generate the HMAC-SHA1 signature that it sends via the `X-Callback-Signature` header. The service includes the header during URL verification and with every notification sent to the callback URL. It calculates the signature over the payload of the notification. If you omit the parameter, the service does not send the header. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if callback_url is None: raise ValueError('callback_url must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=register_callback' params = {'callback_url': callback_url, 'user_secret': user_secret} url = '/v1/register_callback' response = self.request( method='POST', url=url, headers=headers, params=params, accept_json=True) return response def unregister_callback(self, callback_url, **kwargs): """ Unregister a callback. Unregisters a callback URL that was previously white-listed 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 URL](https://cloud.ibm.com/docs/services/speech-to-text/async.html#unregister). :param str callback_url: The callback URL that is to be unregistered. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if callback_url is None: raise ValueError('callback_url must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=unregister_callback' params = {'callback_url': callback_url} url = '/v1/unregister_callback' response = self.request( method='POST', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Custom language models ######################### def create_language_model(self, name, base_model_name, dialect=None, description=None, **kwargs): """ Create a custom language model. Creates a new custom language model for a specified base model. The custom language model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. **See also:** [Create a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#createModel). :param str name: A user-defined name for the new custom language model. Use a name that is unique among all custom language models that you own. Use a localized name that matches the language of the custom model. Use a name that describes the domain of the custom model, such as `Medical custom model` or `Legal custom model`. :param str base_model_name: The name of the base language model that is to be customized by the new custom language model. The new custom model can be used only with the base model that it customizes. To determine whether a base model supports language model customization, use the **Get a model** method and check that the attribute `custom_language_model` is set to `true`. You can also refer to [Language support for customization](https://cloud.ibm.com/docs/services/speech-to-text/custom.html#languageSupport). :param str dialect: The dialect of the specified language that is to be used with the custom language model. The parameter is meaningful only for Spanish models, for which the service creates a custom language model that is suited for speech in one of the following dialects: * `es-ES` for Castilian Spanish (the default) * `es-LA` for Latin American Spanish * `es-US` for North American (Mexican) Spanish A specified dialect must be valid for the base model. By default, the dialect matches the language of the base model; for example, `en-US` for either of the US English language models. :param str description: A description of the new custom language model. Use a localized description that matches the language of the custom model. :param 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 base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=create_language_model' data = { 'name': name, 'base_model_name': base_model_name, 'dialect': dialect, 'description': description } url = '/v1/customizations' response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response def delete_language_model(self, customization_id, **kwargs): """ Delete a custom language model. Deletes an existing custom language model. The custom model cannot be deleted if another request, such as adding a corpus or grammar to the model, is currently being processed. You must use credentials for the instance of the service that owns a model to delete it. **See also:** [Deleting a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#deleteModel). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_language_model' url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_language_model(self, customization_id, **kwargs): """ Get a custom language model. Gets information about a specified custom language model. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom language models](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#listModels). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=get_language_model' url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_language_models(self, language=None, **kwargs): """ List custom language models. Lists information about all custom language models that are owned by an instance of the service. Use the `language` parameter to see all custom language models for the specified language. Omit the parameter to see all custom language models for all languages. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom language models](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#listModels). :param str language: The identifier of the language for which custom language or custom acoustic models are to be returned (for example, `en-US`). Omit the parameter to see all custom language or custom acoustic models that are owned by the requesting credentials. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=list_language_models' params = {'language': language} url = '/v1/customizations' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def reset_language_model(self, customization_id, **kwargs): """ Reset a custom language model. Resets a custom language model by removing all corpora, grammars, and words from the model. Resetting a custom language model initializes the model to its state when it was first created. Metadata such as the name and language of the model are preserved, but the model's words resource is removed and must be re-created. You must use credentials for the instance of the service that owns a model to reset it. **See also:** [Resetting a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#resetModel). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=reset_language_model' url = '/v1/customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, accept_json=True) return response def train_language_model(self, customization_id, word_type_to_add=None, customization_weight=None, **kwargs): """ Train a custom language model. Initiates the training of a custom language model with new resources such as corpora, grammars, and custom words. After adding, modifying, or deleting resources for a custom language model, use this method to begin the actual training of the model on the latest data. You can specify whether the custom language model is to be trained with all words from its words resource or only with words that were added or modified by the user directly. You must use credentials for the instance of the service that owns a model to train it. The training method is asynchronous. It can take on the order of minutes to complete depending on the amount of data on which the service is being trained and the current load on the service. The method returns an HTTP 200 response code to indicate that the training process has begun. You can monitor the status of the training by using the **Get a custom language model** method to poll the model's status. Use a loop to check the status every 10 seconds. The method returns a `LanguageModel` object that includes `status` and `progress` fields. A status of `available` means that the custom model is trained and ready to use. The service cannot accept subsequent training requests or requests to add new resources until the existing request completes. Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as another training request or a request to add a corpus or grammar to the model. * No training data have been added to the custom model. * One or more words that were added to the custom model have invalid sounds-like pronunciations that you must fix. **See also:** [Train the custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#trainModel). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str word_type_to_add: The type of words from the custom language model's words resource on which to train the model: * `all` (the default) trains the model on all new words, regardless of whether they were extracted from corpora or grammars or were added or modified by the user. * `user` trains the model only on new words that were added or modified by the user directly. The model is not trained on new words extracted from corpora or grammars. :param float customization_weight: Specifies a customization weight for the custom language model. The customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for speech recognition. Specify a value between 0.0 and 1.0; the default is 0.3. The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. The value that you assign is used for all recognition requests that use the model. You can override it for any recognition request by specifying a customization weight for that request. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=train_language_model' params = { 'word_type_to_add': word_type_to_add, 'customization_weight': customization_weight } url = '/v1/customizations/{0}/train'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, params=params, accept_json=True) return response def upgrade_language_model(self, customization_id, **kwargs): """ Upgrade a custom language model. Initiates the upgrade of a custom language model to the latest version of its base language model. The upgrade method is asynchronous. It can take on the order of minutes to complete depending on the amount of data in the custom model and the current load on the service. A custom model must be in the `ready` or `available` state to be upgraded. You must use credentials for the instance of the service that owns a model to upgrade it. The method returns an HTTP 200 response code to indicate that the upgrade process has begun successfully. You can monitor the status of the upgrade by using the **Get a custom language model** method to poll the model's status. The method returns a `LanguageModel` object that includes `status` and `progress` fields. Use a loop to check the status every 10 seconds. While it is being upgraded, the custom model has the status `upgrading`. When the upgrade is complete, the model resumes the status that it had prior to upgrade. The service cannot accept subsequent requests for the model until the upgrade completes. **See also:** [Upgrading a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/custom-upgrade.html#upgradeLanguage). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=upgrade_language_model' url = '/v1/customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, accept_json=True) return response ######################### # Custom corpora ######################### def add_corpus(self, customization_id, corpus_name, corpus_file, allow_overwrite=None, corpus_filename=None, **kwargs): """ Add a corpus. Adds a single corpus text file of new training data to a custom language model. Use multiple requests to submit multiple corpus text files. You must use credentials for the instance of the service that owns a model to add a corpus to it. Adding a corpus does not affect the custom language model until you train the model for the new data by using the **Train a custom language model** method. Submit a plain text file that contains sample sentences from the domain of interest to enable the service to extract words in context. The more sentences you add that represent the context in which speakers use words from the domain, the better the service's recognition accuracy. The call returns an HTTP 201 response code if the corpus is valid. The service then asynchronously processes the contents of the corpus and automatically extracts new words that it finds. This can take on the order of a minute or two to complete depending on the total number of words and the number of new words in the corpus, as well as the current load on the service. You cannot submit requests to add additional resources to the custom model or to train the model until the service's analysis of the corpus for the current request completes. Use the **List a corpus** method to check the status of the analysis. The service auto-populates the model's words resource with words from the corpus that are not found in its base vocabulary. These are referred to as out-of-vocabulary (OOV) words. You can use the **List custom words** method to examine the words resource. You can use other words method to eliminate typos and modify how words are pronounced as needed. To add a corpus file that has the same name as an existing corpus, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing corpus causes the service to process the corpus text file and extract OOV words anew. Before doing so, it removes any OOV words associated with the existing corpus from the model's words resource unless they were also added by another corpus or grammar, or they have been modified in some way with the **Add custom words** or **Add a custom word** method. The service limits the overall amount of data that you can add to a custom model to a maximum of 10 million total words from all sources combined. Also, you can add no more than 30 thousand custom (OOV) words to a model. This includes words that the service extracts from corpora and grammars, and words that you add directly. **See also:** * [Working with corpora](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#workingCorpora) * [Add corpora to the custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#addCorpora). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str corpus_name: The name of the new corpus for the custom language model. Use a localized name that matches the language of the custom model and reflects the contents of the corpus. * Include a maximum of 128 characters in the name. * Do not include spaces, slashes, or backslashes in the name. * Do not use the name of an existing corpus or grammar that is already defined for the custom model. * Do not use the name `user`, which is reserved by the service to denote custom words that are added or modified by the user. :param file corpus_file: A plain text file that contains the training data for the corpus. Encode the file in UTF-8 if it contains non-ASCII characters; the service assumes UTF-8 encoding if it encounters non-ASCII characters. Make sure that you know the character encoding of the file. You must use that encoding when working with the words in the custom language model. For more information, see [Character encoding](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#charEncoding). With the `curl` command, use the `--data-binary` option to upload the file for the request. :param bool allow_overwrite: If `true`, the specified corpus overwrites an existing corpus with the same name. If `false`, the request fails if a corpus with the same name already exists. The parameter has no effect if a corpus with the same name does not already exist. :param str corpus_filename: The filename for corpus_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if corpus_name is None: raise ValueError('corpus_name must be provided') if corpus_file is None: raise ValueError('corpus_file must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=add_corpus' params = {'allow_overwrite': allow_overwrite} form_data = {} if not corpus_filename and hasattr(corpus_file, 'name'): corpus_filename = basename(corpus_file.name) form_data['corpus_file'] = (corpus_filename, corpus_file, 'text/plain') url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response def delete_corpus(self, customization_id, corpus_name, **kwargs): """ Delete a corpus. Deletes an existing corpus from a custom language model. The service removes any out-of-vocabulary (OOV) words that are associated with the corpus from the custom model's words resource unless they were also added by another corpus or grammar, or they were modified in some way with the **Add custom words** or **Add a custom word** method. Removing a corpus does not affect the custom model until you train the model with the **Train a custom language model** method. You must use credentials for the instance of the service that owns a model to delete its corpora. **See also:** [Deleting a corpus from a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-corpora.html#deleteCorpus). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str corpus_name: The name of the corpus for the custom language model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if corpus_name is None: raise ValueError('corpus_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_corpus' url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_corpus(self, customization_id, corpus_name, **kwargs): """ Get a corpus. Gets information about a corpus from a custom language model. The information includes the total number of words and out-of-vocabulary (OOV) words, name, and status of the corpus. You must use credentials for the instance of the service that owns a model to list its corpora. **See also:** [Listing corpora for a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-corpora.html#listCorpora). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str corpus_name: The name of the corpus for the custom language model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if corpus_name is None: raise ValueError('corpus_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=get_corpus' url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_corpora(self, customization_id, **kwargs): """ List corpora. Lists information about all corpora from a custom language model. The information includes the total number of words and out-of-vocabulary (OOV) words, name, and status of each corpus. You must use credentials for the instance of the service that owns a model to list its corpora. **See also:** [Listing corpora for a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-corpora.html#listCorpora). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=list_corpora' url = '/v1/customizations/{0}/corpora'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response ######################### # Custom words ######################### def add_word(self, customization_id, word_name, word=None, sounds_like=None, display_as=None, **kwargs): """ Add a custom word. Adds a custom word to a custom language model. The service populates the words resource for a custom model with out-of-vocabulary (OOV) words from each corpus or grammar that is added to the model. You can use this method to add a word or to modify an existing word in the words resource. The words resource for a model can contain a maximum of 30 thousand custom (OOV) words. This includes words that the service extracts from corpora and grammars and words that you add directly. You must use credentials for the instance of the service that owns a model to add or modify a custom word for the model. Adding or modifying a custom word does not affect the custom model until you train the model for the new data by using the **Train a custom language model** method. Use the `word_name` parameter to specify the custom word that is to be added or modified. Use the `CustomWord` object to provide one or both of the optional `sounds_like` and `display_as` fields for the word. * The `sounds_like` field provides an array of one or more pronunciations for the word. Use the parameter to specify how the word can be pronounced by users. Use the parameter for words that are difficult to pronounce, foreign words, acronyms, and so on. For example, you might specify that the word `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like pronunciations for a word. * The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM(trademark)` is to be displayed as `IBM™`. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error, it does not add the word to the words resource. Use the **List a custom word** method to review the word that you add. **See also:** * [Working with custom words](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#workingWords) * [Add words to the custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#addWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str word_name: The custom word that is to be added to or updated in the custom language model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. URL-encode the word if it includes non-ASCII characters. For more information, see [Character encoding](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#charEncoding). :param str word: For the **Add custom words** method, you must specify the custom word that is to be added to or updated in the custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. :param list[str] sounds_like: An array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the parameter to have the service automatically generate a sounds-like pronunciation for the word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. :param str display_as: An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if word_name is None: raise ValueError('word_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=add_word' data = { 'word': word, 'sounds_like': sounds_like, 'display_as': display_as } url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) response = self.request( method='PUT', url=url, headers=headers, json=data, accept_json=True) return response def add_words(self, customization_id, words, **kwargs): """ Add custom words. Adds one or more custom words to a custom language model. The service populates the words resource for a custom model with out-of-vocabulary (OOV) words from each corpus or grammar that is added to the model. You can use this method to add additional words or to modify existing words in the words resource. The words resource for a model can contain a maximum of 30 thousand custom (OOV) words. This includes words that the service extracts from corpora and grammars and words that you add directly. You must use credentials for the instance of the service that owns a model to add or modify custom words for the model. Adding or modifying custom words does not affect the custom model until you train the model for the new data by using the **Train a custom language model** method. You add custom words by providing a `CustomWords` object, which is an array of `CustomWord` objects, one per word. You must use the object's `word` parameter to identify the word that is to be added. You can also provide one or both of the optional `sounds_like` and `display_as` fields for each word. * The `sounds_like` field provides an array of one or more pronunciations for the word. Use the parameter to specify how the word can be pronounced by users. Use the parameter for words that are difficult to pronounce, foreign words, acronyms, and so on. For example, you might specify that the word `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like pronunciations for a word. * The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM(trademark)` is to be displayed as `IBM™`. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error with the input data, it returns a failure code and does not add any of the words to the words resource. The call returns an HTTP 201 response code if the input data is valid. It then asynchronously processes the words to add them to the model's words resource. The time that it takes for the analysis to complete depends on the number of new words that you add but is generally faster than adding a corpus or grammar. You can monitor the status of the request by using the **List a custom language model** method to poll the model's status. Use a loop to check the status every 10 seconds. The method returns a `Customization` object that includes a `status` field. A status of `ready` means that the words have been added to the custom model. The service cannot accept requests to add new data or to train the model until the existing request completes. You can use the **List custom words** or **List a custom word** method to review the words that you add. Words with an invalid `sounds_like` field include an `error` field that describes the problem. You can use other words-related methods to correct errors, eliminate typos, and modify how words are pronounced as needed. **See also:** * [Working with custom words](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#workingWords) * [Add words to the custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#addWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param list[CustomWord] words: An array of `CustomWord` objects that provides information about each custom word that is to be added to or updated in the custom language model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') words = [self._convert_model(x, CustomWord) for x in words] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=add_words' data = {'words': words} url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response def delete_word(self, customization_id, word_name, **kwargs): """ Delete a custom word. Deletes a custom word from a custom language model. You can remove any word that you added to the custom model's words resource via any means. However, if the word also exists in the service's base vocabulary, the service removes only the custom pronunciation for the word; the word remains in the base vocabulary. Removing a custom word does not affect the custom model until you train the model with the **Train a custom language model** method. You must use credentials for the instance of the service that owns a model to delete its words. **See also:** [Deleting a word from a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-words.html#deleteWord). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str word_name: The custom word that is to be deleted from the custom language model. URL-encode the word if it includes non-ASCII characters. For more information, see [Character encoding](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#charEncoding). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if word_name is None: raise ValueError('word_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_word' url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_word(self, customization_id, word_name, **kwargs): """ Get a custom word. Gets information about a custom word from a custom language model. You must use credentials for the instance of the service that owns a model to list information about its words. **See also:** [Listing words from a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-words.html#listWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str word_name: The custom word that is to be read from the custom language model. URL-encode the word if it includes non-ASCII characters. For more information, see [Character encoding](https://cloud.ibm.com/docs/services/speech-to-text/language-resource.html#charEncoding). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if word_name is None: raise ValueError('word_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=get_word' url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_words(self, customization_id, word_type=None, sort=None, **kwargs): """ List custom words. Lists information about custom words from a custom language model. You can list all words from the custom model's words resource, only custom words that were added or modified by the user, or only out-of-vocabulary (OOV) words that were extracted from corpora or are recognized by grammars. You can also indicate the order in which the service is to return words; by default, the service lists words in ascending alphabetical order. You must use credentials for the instance of the service that owns a model to list information about its words. **See also:** [Listing words from a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/language-words.html#listWords). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str word_type: The type of words to be listed from the custom language model's words resource: * `all` (the default) shows all words. * `user` shows only custom words that were added or modified by the user directly. * `corpora` shows only OOV that were extracted from corpora. * `grammars` shows only OOV words that are recognized by grammars. :param str sort: Indicates the order in which the words are to be listed, `alphabetical` or by `count`. You can prepend an optional `+` or `-` to an argument to indicate whether the results are to be sorted in ascending or descending order. By default, words are sorted in ascending alphabetical order. For alphabetical ordering, the lexicographical precedence is numeric values, uppercase letters, and lowercase letters. For count ordering, values with the same count are ordered alphabetically. With the `curl` command, URL encode the `+` symbol as `%2B`. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=list_words' params = {'word_type': word_type, 'sort': sort} url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Custom grammars ######################### def add_grammar(self, customization_id, grammar_name, grammar_file, content_type, allow_overwrite=None, **kwargs): """ Add a grammar. Adds a single grammar file to a custom language model. Submit a plain text file in UTF-8 format that defines the grammar. Use multiple requests to submit multiple grammar files. You must use credentials for the instance of the service that owns a model to add a grammar to it. Adding a grammar does not affect the custom language model until you train the model for the new data by using the **Train a custom language model** method. The call returns an HTTP 201 response code if the grammar is valid. The service then asynchronously processes the contents of the grammar and automatically extracts new words that it finds. This can take a few seconds to complete depending on the size and complexity of the grammar, as well as the current load on the service. You cannot submit requests to add additional resources to the custom model or to train the model until the service's analysis of the grammar for the current request completes. Use the **Get a grammar** method to check the status of the analysis. The service populates the model's words resource with any word that is recognized by the grammar that is not found in the model's base vocabulary. These are referred to as out-of-vocabulary (OOV) words. You can use the **List custom words** method to examine the words resource and use other words-related methods to eliminate typos and modify how words are pronounced as needed. To add a grammar that has the same name as an existing grammar, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing grammar causes the service to process the grammar file and extract OOV words anew. Before doing so, it removes any OOV words associated with the existing grammar from the model's words resource unless they were also added by another resource or they have been modified in some way with the **Add custom words** or **Add a custom word** method. The service limits the overall amount of data that you can add to a custom model to a maximum of 10 million total words from all sources combined. Also, you can add no more than 30 thousand OOV words to a model. This includes words that the service extracts from corpora and grammars and words that you add directly. **See also:** * [Working with grammars](https://cloud.ibm.com/docs/services/speech-to-text/) * [Add grammars to the custom language model](https://cloud.ibm.com/docs/services/speech-to-text/). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str grammar_name: The name of the new grammar for the custom language model. Use a localized name that matches the language of the custom model and reflects the contents of the grammar. * Include a maximum of 128 characters in the name. * Do not include spaces, slashes, or backslashes in the name. * Do not use the name of an existing grammar or corpus that is already defined for the custom model. * Do not use the name `user`, which is reserved by the service to denote custom words that are added or modified by the user. :param str grammar_file: A plain text file that contains the grammar in the format specified by the `Content-Type` header. Encode the file in UTF-8 (ASCII is a subset of UTF-8). Using any other encoding can lead to issues when compiling the grammar or to unexpected results in decoding. The service ignores an encoding that is specified in the header of the grammar. :param str content_type: The format (MIME type) of the grammar file: * `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a plain-text representation that is similar to traditional BNF grammars. * `application/srgs+xml` for XML Form, which uses XML elements to represent the grammar. :param bool allow_overwrite: If `true`, the specified grammar overwrites an existing grammar with the same name. If `false`, the request fails if a grammar with the same name already exists. The parameter has no effect if a grammar with the same name does not already exist. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if grammar_name is None: raise ValueError('grammar_name must be provided') if grammar_file is None: raise ValueError('grammar_file must be provided') if content_type is None: raise ValueError('content_type must be provided') headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=add_grammar' params = {'allow_overwrite': allow_overwrite} data = grammar_file url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) response = self.request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) return response def delete_grammar(self, customization_id, grammar_name, **kwargs): """ Delete a grammar. Deletes an existing grammar from a custom language model. The service removes any out-of-vocabulary (OOV) words associated with the grammar from the custom model's words resource unless they were also added by another resource or they were modified in some way with the **Add custom words** or **Add a custom word** method. Removing a grammar does not affect the custom model until you train the model with the **Train a custom language model** method. You must use credentials for the instance of the service that owns a model to delete its grammar. **See also:** [Deleting a grammar from a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str grammar_name: The name of the grammar for the custom language model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if grammar_name is None: raise ValueError('grammar_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_grammar' url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_grammar(self, customization_id, grammar_name, **kwargs): """ Get a grammar. Gets information about a grammar from a custom language model. The information includes the total number of out-of-vocabulary (OOV) words, name, and status of the grammar. You must use credentials for the instance of the service that owns a model to list its grammars. **See also:** [Listing grammars from a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str grammar_name: The name of the grammar for the custom language model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if grammar_name is None: raise ValueError('grammar_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=get_grammar' url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_grammars(self, customization_id, **kwargs): """ List grammars. Lists information about all grammars from a custom language model. The information includes the total number of out-of-vocabulary (OOV) words, name, and status of each grammar. You must use credentials for the instance of the service that owns a model to list its grammars. **See also:** [Listing grammars from a custom language model](https://cloud.ibm.com/docs/services/speech-to-text/). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=list_grammars' url = '/v1/customizations/{0}/grammars'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response ######################### # Custom acoustic models ######################### def create_acoustic_model(self, name, base_model_name, description=None, **kwargs): """ Create a custom acoustic model. Creates a new custom acoustic model for a specified base model. The custom acoustic model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#createModel). :param str name: A user-defined name for the new custom acoustic model. Use a name that is unique among all custom acoustic models that you own. Use a localized name that matches the language of the custom model. Use a name that describes the acoustic environment of the custom model, such as `Mobile custom model` or `Noisy car custom model`. :param str base_model_name: The name of the base language model that is to be customized by the new custom acoustic model. The new custom model can be used only with the base model that it customizes. To determine whether a base model supports acoustic model customization, refer to [Language support for customization](https://cloud.ibm.com/docs/services/speech-to-text/custom.html#languageSupport). :param str description: A description of the new custom acoustic model. Use a localized description that matches the language of the custom model. :param 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 base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=create_acoustic_model' data = { 'name': name, 'base_model_name': base_model_name, 'description': description } url = '/v1/acoustic_customizations' response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response def delete_acoustic_model(self, customization_id, **kwargs): """ Delete a custom acoustic model. Deletes an existing custom acoustic model. The custom model cannot be deleted if another request, such as adding an audio resource to the model, is currently being processed. You must use credentials for the instance of the service that owns a model to delete it. **See also:** [Deleting a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#deleteModel). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_acoustic_model' url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_acoustic_model(self, customization_id, **kwargs): """ Get a custom acoustic model. Gets information about a specified custom acoustic model. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#listModels). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=get_acoustic_model' url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_acoustic_models(self, language=None, **kwargs): """ List custom acoustic models. Lists information about all custom acoustic models that are owned by an instance of the service. Use the `language` parameter to see all custom acoustic models for the specified language. Omit the parameter to see all custom acoustic models for all languages. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#listModels). :param str language: The identifier of the language for which custom language or custom acoustic models are to be returned (for example, `en-US`). Omit the parameter to see all custom language or custom acoustic models that are owned by the requesting credentials. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=list_acoustic_models' params = {'language': language} url = '/v1/acoustic_customizations' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def reset_acoustic_model(self, customization_id, **kwargs): """ Reset a custom acoustic model. Resets a custom acoustic model by removing all audio resources from the model. Resetting a custom acoustic model initializes the model to its state when it was first created. Metadata such as the name and language of the model are preserved, but the model's audio resources are removed and must be re-created. You must use credentials for the instance of the service that owns a model to reset it. **See also:** [Resetting a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#resetModel). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=reset_acoustic_model' url = '/v1/acoustic_customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, accept_json=True) return response def train_acoustic_model(self, customization_id, custom_language_model_id=None, **kwargs): """ Train a custom acoustic model. Initiates the training of a custom acoustic model with new or changed audio resources. After adding or deleting audio resources for a custom acoustic model, use this method to begin the actual training of the model on the latest audio data. The custom acoustic model does not reflect its changed data until you train it. You must use credentials for the instance of the service that owns a model to train it. The training method is asynchronous. It can take on the order of minutes or hours to complete depending on the total amount of audio data on which the custom acoustic model is being trained and the current load on the service. Typically, training a custom acoustic model takes approximately two to four times the length of its audio data. The range of time depends on the model being trained and the nature of the audio, such as whether the audio is clean or noisy. The method returns an HTTP 200 response code to indicate that the training process has begun. You can monitor the status of the training by using the **Get a custom acoustic model** method to poll the model's status. Use a loop to check the status once a minute. The method returns an `AcousticModel` object that includes `status` and `progress` fields. A status of `available` indicates that the custom model is trained and ready to use. The service cannot accept subsequent training requests, or requests to add new audio resources, until the existing request completes. You can use the optional `custom_language_model_id` parameter to specify the GUID of a separately created custom language model that is to be used during training. Train with a custom language model if you have verbatim transcriptions of the audio files that you have added to the custom model or you have either corpora (text files) or a list of words that are relevant to the contents of the audio files. Both of the custom models must be based on the same version of the same base model for training to succeed. Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as another training request or a request to add audio resources to the model. * The custom model contains less than 10 minutes or more than 100 hours of audio data. * One or more of the custom model's audio resources is invalid. * You passed an incompatible custom language model with the `custom_language_model_id` query parameter. Both custom models must be based on the same version of the same base model. **See also:** [Train the custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#trainModel). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str custom_language_model_id: The customization ID (GUID) of a custom language model that is to be used during training of the custom acoustic model. Specify a custom language model that has been trained with verbatim transcriptions of the audio resources or that contains words that are relevant to the contents of the audio resources. The custom language model must be based on the same version of the same base model as the custom acoustic model. The credentials specified with the request must own both custom models. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=train_acoustic_model' params = {'custom_language_model_id': custom_language_model_id} url = '/v1/acoustic_customizations/{0}/train'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, params=params, accept_json=True) return response def upgrade_acoustic_model(self, customization_id, custom_language_model_id=None, force=None, **kwargs): """ Upgrade a custom acoustic model. Initiates the upgrade of a custom acoustic model to the latest version of its base language model. The upgrade method is asynchronous. It can take on the order of minutes or hours to complete depending on the amount of data in the custom model and the current load on the service; typically, upgrade takes approximately twice the length of the total audio contained in the custom model. A custom model must be in the `ready` or `available` state to be upgraded. You must use credentials for the instance of the service that owns a model to upgrade it. The method returns an HTTP 200 response code to indicate that the upgrade process has begun successfully. You can monitor the status of the upgrade by using the **Get a custom acoustic model** method to poll the model's status. The method returns an `AcousticModel` object that includes `status` and `progress` fields. Use a loop to check the status once a minute. While it is being upgraded, the custom model has the status `upgrading`. When the upgrade is complete, the model resumes the status that it had prior to upgrade. The service cannot accept subsequent requests for the model until the upgrade completes. If the custom acoustic model was trained with a separately created custom language model, you must use the `custom_language_model_id` parameter to specify the GUID of that custom language model. The custom language model must be upgraded before the custom acoustic model can be upgraded. Omit the parameter if the custom acoustic model was not trained with a custom language model. **See also:** [Upgrading a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/custom-upgrade.html#upgradeAcoustic). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str custom_language_model_id: If the custom acoustic model was trained with a custom language model, the customization ID (GUID) of that custom language model. The custom language model must be upgraded before the custom acoustic model can be upgraded. The credentials specified with the request must own both custom models. :param bool force: If `true`, forces the upgrade of a custom acoustic model for which no input data has been modified since it was last trained. Use this parameter only to force the upgrade of a custom acoustic model that is trained with a custom language model, and only if you receive a 400 response code and the message `No input data modified since last training`. See [Upgrading a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/custom-upgrade.html#upgradeAcoustic). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=upgrade_acoustic_model' params = { 'custom_language_model_id': custom_language_model_id, 'force': force } url = '/v1/acoustic_customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Custom audio resources ######################### def add_audio(self, customization_id, audio_name, audio_resource, content_type=None, contained_content_type=None, allow_overwrite=None, **kwargs): """ Add an audio resource. Adds an audio resource to a custom acoustic model. Add audio content that reflects the acoustic characteristics of the audio that you plan to transcribe. You must use credentials for the instance of the service that owns a model to add an audio resource to it. Adding audio data does not affect the custom acoustic model until you train the model for the new data by using the **Train a custom acoustic model** method. You can add individual audio files or an archive file that contains multiple audio files. Adding multiple audio files via a single archive file is significantly more efficient than adding each file individually. You can add audio resources in any format that the service supports for speech recognition. You can use this method to add any number of audio resources to a custom model by calling the method once for each audio or archive file. But the addition of one audio resource must be fully complete before you can add another. You must add a minimum of 10 minutes and a maximum of 100 hours of audio that includes speech, not just silence, to a custom acoustic model before you can train it. No audio resource, audio- or archive-type, can be larger than 100 MB. To add an audio resource that has the same name as an existing audio resource, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. The method is asynchronous. It can take several seconds to complete depending on the duration of the audio and, in the case of an archive file, the total number of audio files being processed. The service returns a 201 response code if the audio is valid. It then asynchronously analyzes the contents of the audio file or files and automatically extracts information about the audio such as its length, sampling rate, and encoding. You cannot submit requests to add additional audio resources to a custom acoustic model, or to train the model, until the service's analysis of all audio files for the current request completes. To determine the status of the service's analysis of the audio, use the **Get an audio resource** method to poll the status of the audio. The method accepts the customization ID of the custom model and the name of the audio resource, and it returns the status of the resource. Use a loop to check the status of the audio every few seconds until it becomes `ok`. **See also:** [Add audio to the custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#addAudio). ### Content types for audio-type resources You can add an individual audio file in any format that the service supports for speech recognition. For an audio-type resource, use the `Content-Type` parameter to specify the audio format (MIME type) of the audio file, including specifying the sampling rate, channels, and endianness where indicated. * `audio/basic` (Use only with narrowband models.) * `audio/flac` * `audio/g729` (Use only with narrowband models.) * `audio/l16` (Specify the sampling rate (`rate`) and optionally the number of channels (`channels`) and endianness (`endianness`) of the audio.) * `audio/mp3` * `audio/mpeg` * `audio/mulaw` (Specify the sampling rate (`rate`) of the audio.) * `audio/ogg` (The service automatically detects the codec of the input audio.) * `audio/ogg;codecs=opus` * `audio/ogg;codecs=vorbis` * `audio/wav` (Provide audio with a maximum of nine channels.) * `audio/webm` (The service automatically detects the codec of the input audio.) * `audio/webm;codecs=opus` * `audio/webm;codecs=vorbis` The sampling rate of an audio file must match the sampling rate of the base model for the custom model: for broadband models, at least 16 kHz; for narrowband models, at least 8 kHz. If the sampling rate of the audio is higher than the minimum required rate, the service down-samples the audio to the appropriate rate. If the sampling rate of the audio is lower than the minimum required rate, the service labels the audio file as `invalid`. **See also:** [Audio formats](https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html). ### Content types for archive-type resources You can add an archive file (**.zip** or **.tar.gz** file) that contains audio files in any format that the service supports for speech recognition. For an archive-type resource, use the `Content-Type` parameter to specify the media type of the archive file: * `application/zip` for a **.zip** file * `application/gzip` for a **.tar.gz** file. All audio files contained in the archive must have the same audio format. Use the `Contained-Content-Type` parameter to specify the format of the contained audio files. The parameter accepts all of the audio formats supported for use with speech recognition and with the `Content-Type` header, including the `rate`, `channels`, and `endianness` parameters that are used with some formats. The default contained audio format is `audio/wav`. ### Naming restrictions for embedded audio files The name of an audio file that is embedded within an archive-type resource must meet the following restrictions: * Include a maximum of 128 characters in the file name; this includes the file extension. * Do not include spaces, slashes, or backslashes in the file name. * Do not use the name of an audio file that has already been added to the custom model as part of an archive-type resource. :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str audio_name: The name of the new audio resource for the custom acoustic model. Use a localized name that matches the language of the custom model and reflects the contents of the resource. * Include a maximum of 128 characters in the name. * Do not include spaces, slashes, or backslashes in the name. * Do not use the name of an audio resource that has already been added to the custom model. :param file audio_resource: The audio resource that is to be added to the custom acoustic model, an individual audio file or an archive file. :param str content_type: For an audio-type resource, the format (MIME type) of the audio. For more information, see **Content types for audio-type resources** in the method description. For an archive-type resource, the media type of the archive file. For more information, see **Content types for archive-type resources** in the method description. :param str contained_content_type: For an archive-type resource, specifies the format of the audio files that are contained in the archive file. The parameter accepts all of the audio formats that are supported for use with speech recognition, including the `rate`, `channels`, and `endianness` parameters that are used with some formats. For more information, see **Content types for audio-type resources** in the method description. :param bool allow_overwrite: If `true`, the specified audio resource overwrites an existing audio resource with the same name. If `false`, the request fails if an audio resource with the same name already exists. The parameter has no effect if an audio resource with the same name does not already exist. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if audio_name is None: raise ValueError('audio_name must be provided') if audio_resource is None: raise ValueError('audio_resource must be provided') headers = { 'Content-Type': content_type, 'Contained-Content-Type': contained_content_type } if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=add_audio' params = {'allow_overwrite': allow_overwrite} data = audio_resource url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) response = self.request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) return response def delete_audio(self, customization_id, audio_name, **kwargs): """ Delete an audio resource. Deletes an existing audio resource from a custom acoustic model. Deleting an archive-type audio resource removes the entire archive of files; the current interface does not allow deletion of individual files from an archive resource. Removing an audio resource does not affect the custom model until you train the model on its updated data by using the **Train a custom acoustic model** method. You must use credentials for the instance of the service that owns a model to delete its audio resources. **See also:** [Deleting an audio resource from a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-audio.html#deleteAudio). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str audio_name: The name of the audio resource for the custom acoustic model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if audio_name is None: raise ValueError('audio_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_audio' url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_audio(self, customization_id, audio_name, **kwargs): """ Get an audio resource. Gets information about an audio resource from a custom acoustic model. The method returns an `AudioListing` object whose fields depend on the type of audio resource that you specify with the method's `audio_name` parameter: * **For an audio-type resource,** the object's fields match those of an `AudioResource` object: `duration`, `name`, `details`, and `status`. * **For an archive-type resource,** the object includes a `container` field whose fields match those of an `AudioResource` object. It also includes an `audio` field, which contains an array of `AudioResource` objects that provides information about the audio files that are contained in the archive. The information includes the status of the specified audio resource. The status is important for checking the service's analysis of a resource that you add to the custom model. * For an audio-type resource, the `status` field is located in the `AudioListing` object. * For an archive-type resource, the `status` field is located in the `AudioResource` object that is returned in the `container` field. You must use credentials for the instance of the service that owns a model to list its audio resources. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-audio.html#listAudio). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param str audio_name: The name of the audio resource for the custom acoustic model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if audio_name is None: raise ValueError('audio_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=get_audio' url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_audio(self, customization_id, **kwargs): """ List audio resources. Lists information about all audio resources from a custom acoustic model. The information includes the name of the resource and information about its audio data, such as its duration. It also includes the status of the audio resource, which is important for checking the service's analysis of the resource in response to a request to add it to the custom acoustic model. You must use credentials for the instance of the service that owns a model to list its audio resources. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-audio.html#listAudio). :param str customization_id: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=list_audio' url = '/v1/acoustic_customizations/{0}/audio'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response ######################### # User data ######################### def delete_user_data(self, customer_id, **kwargs): """ Delete labeled data. Deletes all data that is associated with a specified customer ID. The method 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. **See also:** [Information security](https://cloud.ibm.com/docs/services/speech-to-text/information-security.html). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=speech_to_text;service_version=V1;operation_id=delete_user_data' params = {'customer_id': customer_id} url = '/v1/user_data' response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class AcousticModel(object): """ AcousticModel. :attr str customization_id: The customization ID (GUID) of the custom acoustic model. The **Create a custom acoustic model** method returns only this field of the object; it does not return the other fields. :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :attr str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). :attr list[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single version is shown. :attr str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom acoustic model. :attr str name: (optional) The name of the custom acoustic model. :attr str description: (optional) The description of the custom acoustic model. :attr str base_model_name: (optional) The name of the language model for which the custom acoustic model was created. :attr str status: (optional) The current status of the custom acoustic model: * `pending`: The model was created but is waiting either for training data to be added or for the service to finish analyzing added data. * `ready`: The model contains data and is ready to be trained. * `training`: The model is currently being trained. * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. :attr int progress: (optional) A percentage that indicates the progress of the custom acoustic model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. :attr str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ def __init__(self, customization_id, created=None, language=None, versions=None, owner=None, name=None, description=None, base_model_name=None, status=None, progress=None, warnings=None): """ Initialize a AcousticModel object. :param str customization_id: The customization ID (GUID) of the custom acoustic model. The **Create a custom acoustic model** method returns only this field of the object; it does not return the other fields. :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :param str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). :param list[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single version is shown. :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom acoustic model. :param str name: (optional) The name of the custom acoustic model. :param str description: (optional) The description of the custom acoustic model. :param str base_model_name: (optional) The name of the language model for which the custom acoustic model was created. :param str status: (optional) The current status of the custom acoustic model: * `pending`: The model was created but is waiting either for training data to be added or for the service to finish analyzing added data. * `ready`: The model contains data and is ready to be trained. * `training`: The model is currently being trained. * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. :param int progress: (optional) A percentage that indicates the progress of the custom acoustic model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ self.customization_id = customization_id self.created = created self.language = language self.versions = versions self.owner = owner self.name = name self.description = description self.base_model_name = base_model_name self.status = status self.progress = progress self.warnings = warnings @classmethod def _from_dict(cls, _dict): """Initialize a AcousticModel object from a json dictionary.""" args = {} if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: raise ValueError( 'Required property \'customization_id\' not present in AcousticModel JSON' ) if 'created' in _dict: args['created'] = _dict.get('created') if 'language' in _dict: args['language'] = _dict.get('language') if 'versions' in _dict: args['versions'] = _dict.get('versions') if 'owner' in _dict: args['owner'] = _dict.get('owner') if 'name' in _dict: args['name'] = _dict.get('name') if 'description' in _dict: args['description'] = _dict.get('description') if 'base_model_name' in _dict: args['base_model_name'] = _dict.get('base_model_name') if 'status' in _dict: args['status'] = _dict.get('status') if 'progress' in _dict: args['progress'] = _dict.get('progress') if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customization_id') and self.customization_id is not None: _dict['customization_id'] = self.customization_id if hasattr(self, 'created') and self.created is not None: _dict['created'] = self.created if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'versions') and self.versions is not None: _dict['versions'] = self.versions if hasattr(self, 'owner') and self.owner is not None: _dict['owner'] = self.owner 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, 'base_model_name') and self.base_model_name is not None: _dict['base_model_name'] = self.base_model_name if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'progress') and self.progress is not None: _dict['progress'] = self.progress if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict def __str__(self): """Return a `str` version of this AcousticModel object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class AcousticModels(object): """ AcousticModels. :attr list[AcousticModel] customizations: An array of `AcousticModel` objects that provides information about each available custom acoustic model. The array is empty if the requesting credentials own no custom acoustic models (if no language is specified) or own no custom acoustic models for the specified language. """ def __init__(self, customizations): """ Initialize a AcousticModels object. :param list[AcousticModel] customizations: An array of `AcousticModel` objects that provides information about each available custom acoustic model. The array is empty if the requesting credentials own no custom acoustic models (if no language is specified) or own no custom acoustic models for the specified language. """ self.customizations = customizations @classmethod def _from_dict(cls, _dict): """Initialize a AcousticModels object from a json dictionary.""" args = {} if 'customizations' in _dict: args['customizations'] = [ AcousticModel._from_dict(x) for x in (_dict.get('customizations')) ] else: raise ValueError( 'Required property \'customizations\' not present in AcousticModels JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: _dict['customizations'] = [ x._to_dict() for x in self.customizations ] return _dict def __str__(self): """Return a `str` version of this AcousticModels object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class AudioDetails(object): """ AudioDetails. :attr str type: (optional) The type of the audio resource: * `audio` for an individual audio file * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file that does not contain audio, such as a JPEG file). :attr str codec: (optional) **For an audio-type resource,** the codec in which the audio is encoded. Omitted for an archive-type resource. :attr int frequency: (optional) **For an audio-type resource,** the sampling rate of the audio in Hertz (samples per second). Omitted for an archive-type resource. :attr str compression: (optional) **For an archive-type resource,** the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ def __init__(self, type=None, codec=None, frequency=None, compression=None): """ Initialize a AudioDetails object. :param str type: (optional) The type of the audio resource: * `audio` for an individual audio file * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file that does not contain audio, such as a JPEG file). :param str codec: (optional) **For an audio-type resource,** the codec in which the audio is encoded. Omitted for an archive-type resource. :param int frequency: (optional) **For an audio-type resource,** the sampling rate of the audio in Hertz (samples per second). Omitted for an archive-type resource. :param str compression: (optional) **For an archive-type resource,** the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ self.type = type self.codec = codec self.frequency = frequency self.compression = compression @classmethod def _from_dict(cls, _dict): """Initialize a AudioDetails object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'codec' in _dict: args['codec'] = _dict.get('codec') if 'frequency' in _dict: args['frequency'] = _dict.get('frequency') if 'compression' in _dict: args['compression'] = _dict.get('compression') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'codec') and self.codec is not None: _dict['codec'] = self.codec if hasattr(self, 'frequency') and self.frequency is not None: _dict['frequency'] = self.frequency if hasattr(self, 'compression') and self.compression is not None: _dict['compression'] = self.compression return _dict def __str__(self): """Return a `str` version of this AudioDetails object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class AudioListing(object): """ AudioListing. :attr float duration: (optional) **For an audio-type resource,** the total seconds of audio in the resource. The value is always a whole number. Omitted for an archive-type resource. :attr str name: (optional) **For an audio-type resource,** the user-specified name of the resource. Omitted for an archive-type resource. :attr AudioDetails details: (optional) **For an audio-type resource,** an `AudioDetails` object that provides detailed information about the resource. The object is empty until the service finishes processing the audio. Omitted for an archive-type resource. :attr str status: (optional) **For an audio-type resource,** the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service cannot accept requests to add new audio resources or to train the custom model until its analysis is complete. * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. :attr AudioResource container: (optional) **For an archive-type resource,** an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. :attr list[AudioResource] audio: (optional) **For an archive-type resource,** an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. """ def __init__(self, duration=None, name=None, details=None, status=None, container=None, audio=None): """ Initialize a AudioListing object. :param float duration: (optional) **For an audio-type resource,** the total seconds of audio in the resource. The value is always a whole number. Omitted for an archive-type resource. :param str name: (optional) **For an audio-type resource,** the user-specified name of the resource. Omitted for an archive-type resource. :param AudioDetails details: (optional) **For an audio-type resource,** an `AudioDetails` object that provides detailed information about the resource. The object is empty until the service finishes processing the audio. Omitted for an archive-type resource. :param str status: (optional) **For an audio-type resource,** the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service cannot accept requests to add new audio resources or to train the custom model until its analysis is complete. * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. :param AudioResource container: (optional) **For an archive-type resource,** an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. :param list[AudioResource] audio: (optional) **For an archive-type resource,** an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. """ self.duration = duration self.name = name self.details = details self.status = status self.container = container self.audio = audio @classmethod def _from_dict(cls, _dict): """Initialize a AudioListing object from a json dictionary.""" args = {} if 'duration' in _dict: args['duration'] = _dict.get('duration') if 'name' in _dict: args['name'] = _dict.get('name') if 'details' in _dict: args['details'] = AudioDetails._from_dict(_dict.get('details')) if 'status' in _dict: args['status'] = _dict.get('status') if 'container' in _dict: args['container'] = AudioResource._from_dict(_dict.get('container')) if 'audio' in _dict: args['audio'] = [ AudioResource._from_dict(x) for x in (_dict.get('audio')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'duration') and self.duration is not None: _dict['duration'] = self.duration if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: _dict['details'] = self.details._to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'container') and self.container is not None: _dict['container'] = self.container._to_dict() if hasattr(self, 'audio') and self.audio is not None: _dict['audio'] = [x._to_dict() for x in self.audio] return _dict def __str__(self): """Return a `str` version of this AudioListing object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class AudioResource(object): """ AudioResource. :attr float duration: The total seconds of audio in the audio resource. The value is always a whole number. :attr str name: **For an archive-type resource,** the user-specified name of the resource. **For an audio-type resource,** the user-specified name of the resource or the name of the audio file that the user added for the resource. The value depends on the method that is called. :attr AudioDetails details: An `AudioDetails` object that provides detailed information about the audio resource. The object is empty until the service finishes processing the audio. :attr str status: The status of the audio resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service cannot accept requests to add new audio resources or to train the custom model until its analysis is complete. * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). For an archive file, the entire archive is invalid if any of its audio files are invalid. """ def __init__(self, duration, name, details, status): """ Initialize a AudioResource object. :param float duration: The total seconds of audio in the audio resource. The value is always a whole number. :param str name: **For an archive-type resource,** the user-specified name of the resource. **For an audio-type resource,** the user-specified name of the resource or the name of the audio file that the user added for the resource. The value depends on the method that is called. :param AudioDetails details: An `AudioDetails` object that provides detailed information about the audio resource. The object is empty until the service finishes processing the audio. :param str status: The status of the audio resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service cannot accept requests to add new audio resources or to train the custom model until its analysis is complete. * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). For an archive file, the entire archive is invalid if any of its audio files are invalid. """ self.duration = duration self.name = name self.details = details self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a AudioResource object from a json dictionary.""" args = {} if 'duration' in _dict: args['duration'] = _dict.get('duration') else: raise ValueError( 'Required property \'duration\' not present in AudioResource JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in AudioResource JSON') if 'details' in _dict: args['details'] = AudioDetails._from_dict(_dict.get('details')) else: raise ValueError( 'Required property \'details\' not present in AudioResource JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in AudioResource JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'duration') and self.duration is not None: _dict['duration'] = self.duration if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: _dict['details'] = self.details._to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this AudioResource object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class AudioResources(object): """ AudioResources. :attr float total_minutes_of_audio: The total minutes of accumulated audio summed over all of the valid audio resources for the custom acoustic model. You can use this value to determine whether the custom model has too little or too much audio to begin training. :attr list[AudioResource] audio: An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic model. The array is empty if the custom model has no audio resources. """ def __init__(self, total_minutes_of_audio, audio): """ Initialize a AudioResources object. :param float total_minutes_of_audio: The total minutes of accumulated audio summed over all of the valid audio resources for the custom acoustic model. You can use this value to determine whether the custom model has too little or too much audio to begin training. :param list[AudioResource] audio: An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic model. The array is empty if the custom model has no audio resources. """ self.total_minutes_of_audio = total_minutes_of_audio self.audio = audio @classmethod def _from_dict(cls, _dict): """Initialize a AudioResources object from a json dictionary.""" args = {} if 'total_minutes_of_audio' in _dict: args['total_minutes_of_audio'] = _dict.get('total_minutes_of_audio') else: raise ValueError( 'Required property \'total_minutes_of_audio\' not present in AudioResources JSON' ) if 'audio' in _dict: args['audio'] = [ AudioResource._from_dict(x) for x in (_dict.get('audio')) ] else: raise ValueError( 'Required property \'audio\' not present in AudioResources JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'total_minutes_of_audio' ) and self.total_minutes_of_audio is not None: _dict['total_minutes_of_audio'] = self.total_minutes_of_audio if hasattr(self, 'audio') and self.audio is not None: _dict['audio'] = [x._to_dict() for x in self.audio] return _dict def __str__(self): """Return a `str` version of this AudioResources object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Corpora(object): """ Corpora. :attr list[Corpus] corpora: An array of `Corpus` objects that provides information about the corpora for the custom model. The array is empty if the custom model has no corpora. """ def __init__(self, corpora): """ Initialize a Corpora object. :param list[Corpus] corpora: An array of `Corpus` objects that provides information about the corpora for the custom model. The array is empty if the custom model has no corpora. """ self.corpora = corpora @classmethod def _from_dict(cls, _dict): """Initialize a Corpora object from a json dictionary.""" args = {} if 'corpora' in _dict: args['corpora'] = [ Corpus._from_dict(x) for x in (_dict.get('corpora')) ] else: raise ValueError( 'Required property \'corpora\' not present in Corpora JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'corpora') and self.corpora is not None: _dict['corpora'] = [x._to_dict() for x in self.corpora] return _dict def __str__(self): """Return a `str` version of this Corpora object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Corpus(object): """ Corpus. :attr str name: The name of the corpus. :attr int total_words: The total number of words in the corpus. The value is `0` while the corpus is being processed. :attr int out_of_vocabulary_words: The number of OOV words in the corpus. The value is `0` while the corpus is being processed. :attr str status: The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the corpus. * `being_processed`: The service is still analyzing the corpus. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. :attr str error: (optional) If the status of the corpus is `undetermined`, the following message: `Analysis of corpus 'name' failed. Please try adding the corpus again by setting the 'allow_overwrite' flag to 'true'`. """ def __init__(self, name, total_words, out_of_vocabulary_words, status, error=None): """ Initialize a Corpus object. :param str name: The name of the corpus. :param int total_words: The total number of words in the corpus. The value is `0` while the corpus is being processed. :param int out_of_vocabulary_words: The number of OOV words in the corpus. The value is `0` while the corpus is being processed. :param str status: The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the corpus. * `being_processed`: The service is still analyzing the corpus. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. :param str error: (optional) If the status of the corpus is `undetermined`, the following message: `Analysis of corpus 'name' failed. Please try adding the corpus again by setting the 'allow_overwrite' flag to 'true'`. """ self.name = name self.total_words = total_words self.out_of_vocabulary_words = out_of_vocabulary_words self.status = status self.error = error @classmethod def _from_dict(cls, _dict): """Initialize a Corpus object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Corpus JSON') if 'total_words' in _dict: args['total_words'] = _dict.get('total_words') else: raise ValueError( 'Required property \'total_words\' not present in Corpus JSON') if 'out_of_vocabulary_words' in _dict: args['out_of_vocabulary_words'] = _dict.get( 'out_of_vocabulary_words') else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Corpus JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in Corpus JSON') if 'error' in _dict: args['error'] = _dict.get('error') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'total_words') and self.total_words is not None: _dict['total_words'] = self.total_words if hasattr(self, 'out_of_vocabulary_words' ) and self.out_of_vocabulary_words is not None: _dict['out_of_vocabulary_words'] = self.out_of_vocabulary_words if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'error') and self.error is not None: _dict['error'] = self.error return _dict def __str__(self): """Return a `str` version of this Corpus object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CustomWord(object): """ CustomWord. :attr str word: (optional) For the **Add custom words** method, you must specify the custom word that is to be added to or updated in the custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. :attr list[str] sounds_like: (optional) An array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the parameter to have the service automatically generate a sounds-like pronunciation for the word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. :attr str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. """ def __init__(self, word=None, sounds_like=None, display_as=None): """ Initialize a CustomWord object. :param str word: (optional) For the **Add custom words** method, you must specify the custom word that is to be added to or updated in the custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. :param list[str] sounds_like: (optional) An array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the parameter to have the service automatically generate a sounds-like pronunciation for the word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. """ self.word = word self.sounds_like = sounds_like self.display_as = display_as @classmethod def _from_dict(cls, _dict): """Initialize a CustomWord object from a json dictionary.""" args = {} if 'word' in _dict: args['word'] = _dict.get('word') if 'sounds_like' in _dict: args['sounds_like'] = _dict.get('sounds_like') if 'display_as' in _dict: args['display_as'] = _dict.get('display_as') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: _dict['display_as'] = self.display_as return _dict def __str__(self): """Return a `str` version of this CustomWord object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Grammar(object): """ Grammar. :attr str name: The name of the grammar. :attr int out_of_vocabulary_words: The number of OOV words in the grammar. The value is `0` while the grammar is being processed. :attr str status: The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can be trained with data from the grammar. * `being_processed`: The service is still analyzing the grammar. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. :attr str error: (optional) If the status of the grammar is `undetermined`, the following message: `Analysis of grammar '{grammar_name}' failed. Please try fixing the error or adding the grammar again by setting the 'allow_overwrite' flag to 'true'.`. """ def __init__(self, name, out_of_vocabulary_words, status, error=None): """ Initialize a Grammar object. :param str name: The name of the grammar. :param int out_of_vocabulary_words: The number of OOV words in the grammar. The value is `0` while the grammar is being processed. :param str status: The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can be trained with data from the grammar. * `being_processed`: The service is still analyzing the grammar. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. :param str error: (optional) If the status of the grammar is `undetermined`, the following message: `Analysis of grammar '{grammar_name}' failed. Please try fixing the error or adding the grammar again by setting the 'allow_overwrite' flag to 'true'.`. """ self.name = name self.out_of_vocabulary_words = out_of_vocabulary_words self.status = status self.error = error @classmethod def _from_dict(cls, _dict): """Initialize a Grammar object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Grammar JSON') if 'out_of_vocabulary_words' in _dict: args['out_of_vocabulary_words'] = _dict.get( 'out_of_vocabulary_words') else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Grammar JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in Grammar JSON') if 'error' in _dict: args['error'] = _dict.get('error') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'out_of_vocabulary_words' ) and self.out_of_vocabulary_words is not None: _dict['out_of_vocabulary_words'] = self.out_of_vocabulary_words if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'error') and self.error is not None: _dict['error'] = self.error return _dict def __str__(self): """Return a `str` version of this Grammar object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Grammars(object): """ Grammars. :attr list[Grammar] grammars: An array of `Grammar` objects that provides information about the grammars for the custom model. The array is empty if the custom model has no grammars. """ def __init__(self, grammars): """ Initialize a Grammars object. :param list[Grammar] grammars: An array of `Grammar` objects that provides information about the grammars for the custom model. The array is empty if the custom model has no grammars. """ self.grammars = grammars @classmethod def _from_dict(cls, _dict): """Initialize a Grammars object from a json dictionary.""" args = {} if 'grammars' in _dict: args['grammars'] = [ Grammar._from_dict(x) for x in (_dict.get('grammars')) ] else: raise ValueError( 'Required property \'grammars\' not present in Grammars JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'grammars') and self.grammars is not None: _dict['grammars'] = [x._to_dict() for x in self.grammars] return _dict def __str__(self): """Return a `str` version of this Grammars object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class KeywordResult(object): """ KeywordResult. :attr str normalized_text: A specified keyword normalized to the spoken phrase that matched in the audio input. :attr float start_time: The start time in seconds of the keyword match. :attr float end_time: The end time in seconds of the keyword match. :attr float confidence: A confidence score for the keyword match in the range of 0.0 to 1.0. """ def __init__(self, normalized_text, start_time, end_time, confidence): """ Initialize a KeywordResult object. :param str normalized_text: A specified keyword normalized to the spoken phrase that matched in the audio input. :param float start_time: The start time in seconds of the keyword match. :param float end_time: The end time in seconds of the keyword match. :param float confidence: A confidence score for the keyword match in the range of 0.0 to 1.0. """ self.normalized_text = normalized_text self.start_time = start_time self.end_time = end_time self.confidence = confidence @classmethod def _from_dict(cls, _dict): """Initialize a KeywordResult object from a json dictionary.""" args = {} if 'normalized_text' in _dict: args['normalized_text'] = _dict.get('normalized_text') else: raise ValueError( 'Required property \'normalized_text\' not present in KeywordResult JSON' ) if 'start_time' in _dict: args['start_time'] = _dict.get('start_time') else: raise ValueError( 'Required property \'start_time\' not present in KeywordResult JSON' ) if 'end_time' in _dict: args['end_time'] = _dict.get('end_time') else: raise ValueError( 'Required property \'end_time\' not present in KeywordResult JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: raise ValueError( 'Required property \'confidence\' not present in KeywordResult JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'normalized_text') and self.normalized_text is not None: _dict['normalized_text'] = self.normalized_text if hasattr(self, 'start_time') and self.start_time is not None: _dict['start_time'] = self.start_time if hasattr(self, 'end_time') and self.end_time is not None: _dict['end_time'] = self.end_time if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence return _dict def __str__(self): """Return a `str` version of this KeywordResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LanguageModel(object): """ LanguageModel. :attr str customization_id: The customization ID (GUID) of the custom language model. The **Create a custom language model** method returns only this field of the object; it does not return the other fields. :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :attr str language: (optional) The language identifier of the custom language model (for example, `en-US`). :attr str dialect: (optional) The dialect of the language for the custom language model. By default, the dialect matches the language of the base model; for example, `en-US` for either of the US English language models. For Spanish models, the field indicates the dialect for which the model was created: * `es-ES` for Castilian Spanish (the default) * `es-LA` for Latin American Spanish * `es-US` for North American (Mexican) Spanish. :attr list[str] versions: (optional) A list of the available versions of the custom language model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single version is shown. :attr str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. :attr str name: (optional) The name of the custom language model. :attr str description: (optional) The description of the custom language model. :attr str base_model_name: (optional) The name of the language model for which the custom language model was created. :attr str status: (optional) The current status of the custom language model: * `pending`: The model was created but is waiting either for training data to be added or for the service to finish analyzing added data. * `ready`: The model contains data and is ready to be trained. * `training`: The model is currently being trained. * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. :attr int progress: (optional) A percentage that indicates the progress of the custom language model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. :attr str error: (optional) If an error occurred while adding a grammar file to the custom language model, a message that describes an `Internal Server Error` and includes the string `Cannot compile grammar`. The status of the custom model is not affected by the error, but the grammar cannot be used with the model. :attr str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ def __init__(self, customization_id, created=None, language=None, dialect=None, versions=None, owner=None, name=None, description=None, base_model_name=None, status=None, progress=None, error=None, warnings=None): """ Initialize a LanguageModel object. :param str customization_id: The customization ID (GUID) of the custom language model. The **Create a custom language model** method returns only this field of the object; it does not return the other fields. :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :param str language: (optional) The language identifier of the custom language model (for example, `en-US`). :param str dialect: (optional) The dialect of the language for the custom language model. By default, the dialect matches the language of the base model; for example, `en-US` for either of the US English language models. For Spanish models, the field indicates the dialect for which the model was created: * `es-ES` for Castilian Spanish (the default) * `es-LA` for Latin American Spanish * `es-US` for North American (Mexican) Spanish. :param list[str] versions: (optional) A list of the available versions of the custom language model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single version is shown. :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. :param str name: (optional) The name of the custom language model. :param str description: (optional) The description of the custom language model. :param str base_model_name: (optional) The name of the language model for which the custom language model was created. :param str status: (optional) The current status of the custom language model: * `pending`: The model was created but is waiting either for training data to be added or for the service to finish analyzing added data. * `ready`: The model contains data and is ready to be trained. * `training`: The model is currently being trained. * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. :param int progress: (optional) A percentage that indicates the progress of the custom language model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. :param str error: (optional) If an error occurred while adding a grammar file to the custom language model, a message that describes an `Internal Server Error` and includes the string `Cannot compile grammar`. The status of the custom model is not affected by the error, but the grammar cannot be used with the model. :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ self.customization_id = customization_id self.created = created self.language = language self.dialect = dialect self.versions = versions self.owner = owner self.name = name self.description = description self.base_model_name = base_model_name self.status = status self.progress = progress self.error = error self.warnings = warnings @classmethod def _from_dict(cls, _dict): """Initialize a LanguageModel object from a json dictionary.""" args = {} if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: raise ValueError( 'Required property \'customization_id\' not present in LanguageModel JSON' ) if 'created' in _dict: args['created'] = _dict.get('created') if 'language' in _dict: args['language'] = _dict.get('language') if 'dialect' in _dict: args['dialect'] = _dict.get('dialect') if 'versions' in _dict: args['versions'] = _dict.get('versions') if 'owner' in _dict: args['owner'] = _dict.get('owner') if 'name' in _dict: args['name'] = _dict.get('name') if 'description' in _dict: args['description'] = _dict.get('description') if 'base_model_name' in _dict: args['base_model_name'] = _dict.get('base_model_name') if 'status' in _dict: args['status'] = _dict.get('status') if 'progress' in _dict: args['progress'] = _dict.get('progress') if 'error' in _dict: args['error'] = _dict.get('error') if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customization_id') and self.customization_id is not None: _dict['customization_id'] = self.customization_id if hasattr(self, 'created') and self.created is not None: _dict['created'] = self.created if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'dialect') and self.dialect is not None: _dict['dialect'] = self.dialect if hasattr(self, 'versions') and self.versions is not None: _dict['versions'] = self.versions if hasattr(self, 'owner') and self.owner is not None: _dict['owner'] = self.owner 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, 'base_model_name') and self.base_model_name is not None: _dict['base_model_name'] = self.base_model_name if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'progress') and self.progress is not None: _dict['progress'] = self.progress if hasattr(self, 'error') and self.error is not None: _dict['error'] = self.error if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict def __str__(self): """Return a `str` version of this LanguageModel object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LanguageModels(object): """ LanguageModels. :attr list[LanguageModel] customizations: An array of `LanguageModel` objects that provides information about each available custom language model. The array is empty if the requesting credentials own no custom language models (if no language is specified) or own no custom language models for the specified language. """ def __init__(self, customizations): """ Initialize a LanguageModels object. :param list[LanguageModel] customizations: An array of `LanguageModel` objects that provides information about each available custom language model. The array is empty if the requesting credentials own no custom language models (if no language is specified) or own no custom language models for the specified language. """ self.customizations = customizations @classmethod def _from_dict(cls, _dict): """Initialize a LanguageModels object from a json dictionary.""" args = {} if 'customizations' in _dict: args['customizations'] = [ LanguageModel._from_dict(x) for x in (_dict.get('customizations')) ] else: raise ValueError( 'Required property \'customizations\' not present in LanguageModels JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: _dict['customizations'] = [ x._to_dict() for x in self.customizations ] return _dict def __str__(self): """Return a `str` version of this LanguageModels object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RecognitionJob(object): """ RecognitionJob. :attr str id: The ID of the asynchronous job. :attr str status: The current status of the job: * `waiting`: The service is preparing the job for processing. The service returns this status when the job is initially created or when it is waiting for capacity to process the job. The job remains in this state until the service has the capacity to begin processing it. * `processing`: The service is actively processing the job. * `completed`: The service has finished processing the job. If the job specified a callback URL and the event `recognitions.completed_with_results`, the service sent the results with the callback notification. Otherwise, you must retrieve the results by checking the individual job. * `failed`: The job failed. :attr str created: The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :attr str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only by the **Check jobs** and **Check a job** methods. :attr str url: (optional) The URL to use to request information about the job with the **Check a job** method. This field is returned only by the **Create a job** method. :attr str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by the **Check jobs** method. :attr list[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned only by the **Check a job** method. :attr list[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field can be returned only by the **Create a job** method. """ def __init__(self, id, status, created, updated=None, url=None, user_token=None, results=None, warnings=None): """ Initialize a RecognitionJob object. :param str id: The ID of the asynchronous job. :param str status: The current status of the job: * `waiting`: The service is preparing the job for processing. The service returns this status when the job is initially created or when it is waiting for capacity to process the job. The job remains in this state until the service has the capacity to begin processing it. * `processing`: The service is actively processing the job. * `completed`: The service has finished processing the job. If the job specified a callback URL and the event `recognitions.completed_with_results`, the service sent the results with the callback notification. Otherwise, you must retrieve the results by checking the individual job. * `failed`: The job failed. :param str created: The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only by the **Check jobs** and **Check a job** methods. :param str url: (optional) The URL to use to request information about the job with the **Check a job** method. This field is returned only by the **Create a job** method. :param str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by the **Check jobs** method. :param list[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned only by the **Check a job** method. :param list[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field can be returned only by the **Create a job** method. """ self.id = id self.status = status self.created = created self.updated = updated self.url = url self.user_token = user_token self.results = results self.warnings = warnings @classmethod def _from_dict(cls, _dict): """Initialize a RecognitionJob object from a json dictionary.""" args = {} if 'id' in _dict: args['id'] = _dict.get('id') else: raise ValueError( 'Required property \'id\' not present in RecognitionJob JSON') if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in RecognitionJob JSON' ) if 'created' in _dict: args['created'] = _dict.get('created') else: raise ValueError( 'Required property \'created\' not present in RecognitionJob JSON' ) if 'updated' in _dict: args['updated'] = _dict.get('updated') if 'url' in _dict: args['url'] = _dict.get('url') if 'user_token' in _dict: args['user_token'] = _dict.get('user_token') if 'results' in _dict: args['results'] = [ SpeechRecognitionResults._from_dict(x) for x in (_dict.get('results')) ] if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'created') and self.created is not None: _dict['created'] = self.created if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = self.updated if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'user_token') and self.user_token is not None: _dict['user_token'] = self.user_token if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict def __str__(self): """Return a `str` version of this RecognitionJob object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RecognitionJobs(object): """ RecognitionJobs. :attr list[RecognitionJob] recognitions: An array of `RecognitionJob` objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs. """ def __init__(self, recognitions): """ Initialize a RecognitionJobs object. :param list[RecognitionJob] recognitions: An array of `RecognitionJob` objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs. """ self.recognitions = recognitions @classmethod def _from_dict(cls, _dict): """Initialize a RecognitionJobs object from a json dictionary.""" args = {} if 'recognitions' in _dict: args['recognitions'] = [ RecognitionJob._from_dict(x) for x in (_dict.get('recognitions')) ] else: raise ValueError( 'Required property \'recognitions\' not present in RecognitionJobs JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'recognitions') and self.recognitions is not None: _dict['recognitions'] = [x._to_dict() for x in self.recognitions] return _dict def __str__(self): """Return a `str` version of this RecognitionJobs object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RegisterStatus(object): """ RegisterStatus. :attr str status: The current status of the job: * `created`: The service successfully white-listed the callback URL as a result of the call. * `already created`: The URL was already white-listed. :attr str url: The callback URL that is successfully registered. """ def __init__(self, status, url): """ Initialize a RegisterStatus object. :param str status: The current status of the job: * `created`: The service successfully white-listed the callback URL as a result of the call. * `already created`: The URL was already white-listed. :param str url: The callback URL that is successfully registered. """ self.status = status self.url = url @classmethod def _from_dict(cls, _dict): """Initialize a RegisterStatus object from a json dictionary.""" args = {} if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in RegisterStatus JSON' ) if 'url' in _dict: args['url'] = _dict.get('url') else: raise ValueError( 'Required property \'url\' not present in RegisterStatus JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url return _dict def __str__(self): """Return a `str` version of this RegisterStatus object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SpeakerLabelsResult(object): """ SpeakerLabelsResult. :attr float from_: The start time of a word from the transcript. The value matches the start time of a word from the `timestamps` array. :attr float to: The end time of a word from the transcript. The value matches the end time of a word from the `timestamps` array. :attr int speaker: The numeric identifier that the service assigns to a speaker from the audio. Speaker IDs begin at `0` initially but can evolve and change across interim results (if supported by the method) and between interim and final results as the service processes the audio. They are not guaranteed to be sequential, contiguous, or ordered. :attr float confidence: A score that indicates the service's confidence in its identification of the speaker in the range of 0.0 to 1.0. :attr bool final_results: An indication of whether the service might further change word and speaker-label results. A value of `true` means that the service guarantees not to send any further updates for the current or any preceding results; `false` means that the service might send further updates to the results. """ def __init__(self, from_, to, speaker, confidence, final_results): """ Initialize a SpeakerLabelsResult object. :param float from_: The start time of a word from the transcript. The value matches the start time of a word from the `timestamps` array. :param float to: The end time of a word from the transcript. The value matches the end time of a word from the `timestamps` array. :param int speaker: The numeric identifier that the service assigns to a speaker from the audio. Speaker IDs begin at `0` initially but can evolve and change across interim results (if supported by the method) and between interim and final results as the service processes the audio. They are not guaranteed to be sequential, contiguous, or ordered. :param float confidence: A score that indicates the service's confidence in its identification of the speaker in the range of 0.0 to 1.0. :param bool final_results: An indication of whether the service might further change word and speaker-label results. A value of `true` means that the service guarantees not to send any further updates for the current or any preceding results; `false` means that the service might send further updates to the results. """ self.from_ = from_ self.to = to self.speaker = speaker self.confidence = confidence self.final_results = final_results @classmethod def _from_dict(cls, _dict): """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} if 'from' in _dict: args['from_'] = _dict.get('from') else: raise ValueError( 'Required property \'from\' not present in SpeakerLabelsResult JSON' ) if 'to' in _dict: args['to'] = _dict.get('to') else: raise ValueError( 'Required property \'to\' not present in SpeakerLabelsResult JSON' ) if 'speaker' in _dict: args['speaker'] = _dict.get('speaker') else: raise ValueError( 'Required property \'speaker\' not present in SpeakerLabelsResult JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: raise ValueError( 'Required property \'confidence\' not present in SpeakerLabelsResult JSON' ) if 'final' in _dict or 'final_results' in _dict: args['final_results'] = _dict.get('final') or _dict.get( 'final_results') else: raise ValueError( 'Required property \'final\' not present in SpeakerLabelsResult JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'from_') and self.from_ is not None: _dict['from'] = self.from_ if hasattr(self, 'to') and self.to is not None: _dict['to'] = self.to if hasattr(self, 'speaker') and self.speaker is not None: _dict['speaker'] = self.speaker if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'final_results') and self.final_results is not None: _dict['final'] = self.final_results return _dict def __str__(self): """Return a `str` version of this SpeakerLabelsResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SpeechModel(object): """ SpeechModel. :attr str name: The name of the model for use as an identifier in calls to the service (for example, `en-US_BroadbandModel`). :attr str language: The language identifier of the model (for example, `en-US`). :attr int rate: The sampling rate (minimum acceptable rate for audio) used by the model in Hertz. :attr str url: The URI for the model. :attr SupportedFeatures supported_features: Describes the additional service features that are supported with the model. :attr str description: A brief description of the model. """ def __init__(self, name, language, rate, url, supported_features, description): """ Initialize a SpeechModel object. :param str name: The name of the model for use as an identifier in calls to the service (for example, `en-US_BroadbandModel`). :param str language: The language identifier of the model (for example, `en-US`). :param int rate: The sampling rate (minimum acceptable rate for audio) used by the model in Hertz. :param str url: The URI for the model. :param SupportedFeatures supported_features: Describes the additional service features that are supported with the model. :param str description: A brief description of the model. """ self.name = name self.language = language self.rate = rate self.url = url self.supported_features = supported_features self.description = description @classmethod def _from_dict(cls, _dict): """Initialize a SpeechModel object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in SpeechModel JSON') if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in SpeechModel JSON' ) if 'rate' in _dict: args['rate'] = _dict.get('rate') else: raise ValueError( 'Required property \'rate\' not present in SpeechModel JSON') if 'url' in _dict: args['url'] = _dict.get('url') else: raise ValueError( 'Required property \'url\' not present in SpeechModel JSON') if 'supported_features' in _dict: args['supported_features'] = SupportedFeatures._from_dict( _dict.get('supported_features')) else: raise ValueError( 'Required property \'supported_features\' not present in SpeechModel JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') else: raise ValueError( 'Required property \'description\' not present in SpeechModel JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'rate') and self.rate is not None: _dict['rate'] = self.rate if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr( self, 'supported_features') and self.supported_features is not None: _dict['supported_features'] = self.supported_features._to_dict() if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict def __str__(self): """Return a `str` version of this SpeechModel object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SpeechModels(object): """ SpeechModels. :attr list[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ def __init__(self, models): """ Initialize a SpeechModels object. :param list[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ self.models = models @classmethod def _from_dict(cls, _dict): """Initialize a SpeechModels object from a json dictionary.""" args = {} if 'models' in _dict: args['models'] = [ SpeechModel._from_dict(x) for x in (_dict.get('models')) ] else: raise ValueError( 'Required property \'models\' not present in SpeechModels JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict def __str__(self): """Return a `str` version of this SpeechModels object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SpeechRecognitionAlternative(object): """ SpeechRecognitionAlternative. :attr str transcript: A transcription of the audio. :attr float confidence: (optional) A score that indicates the service's confidence in the transcript in the range of 0.0 to 1.0. A confidence score is returned only for the best alternative and only with results marked as final. :attr list[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. :attr list[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the best alternative and only with results marked as final. """ def __init__(self, transcript, confidence=None, timestamps=None, word_confidence=None): """ Initialize a SpeechRecognitionAlternative object. :param str transcript: A transcription of the audio. :param float confidence: (optional) A score that indicates the service's confidence in the transcript in the range of 0.0 to 1.0. A confidence score is returned only for the best alternative and only with results marked as final. :param list[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. :param list[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the best alternative and only with results marked as final. """ self.transcript = transcript self.confidence = confidence self.timestamps = timestamps self.word_confidence = word_confidence @classmethod def _from_dict(cls, _dict): """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} if 'transcript' in _dict: args['transcript'] = _dict.get('transcript') else: raise ValueError( 'Required property \'transcript\' not present in SpeechRecognitionAlternative JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'timestamps' in _dict: args['timestamps'] = _dict.get('timestamps') if 'word_confidence' in _dict: args['word_confidence'] = _dict.get('word_confidence') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'transcript') and self.transcript is not None: _dict['transcript'] = self.transcript if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'timestamps') and self.timestamps is not None: _dict['timestamps'] = self.timestamps if hasattr(self, 'word_confidence') and self.word_confidence is not None: _dict['word_confidence'] = self.word_confidence return _dict def __str__(self): """Return a `str` version of this SpeechRecognitionAlternative object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SpeechRecognitionResult(object): """ SpeechRecognitionResult. :attr bool final_results: An indication of whether the transcription results are final. If `true`, the results for this utterance are not updated further; no additional results are sent for a `result_index` once its results are indicated as final. :attr list[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. :attr dict keywords_result: (optional) A dictionary (or associative array) whose keys are the strings specified for `keywords` if both that parameter and `keywords_threshold` are specified. The value for each key is an array of matches spotted in the audio for that keyword. Each match is described by a `KeywordResult` object. A keyword for which no matches are found is omitted from the dictionary. The dictionary is omitted entirely if no matches are found for any keywords. :attr list[WordAlternativeResults] word_alternatives: (optional) An array of alternative hypotheses found for words of the input audio if a `word_alternatives_threshold` is specified. """ def __init__(self, final_results, alternatives, keywords_result=None, word_alternatives=None): """ Initialize a SpeechRecognitionResult object. :param bool final_results: An indication of whether the transcription results are final. If `true`, the results for this utterance are not updated further; no additional results are sent for a `result_index` once its results are indicated as final. :param list[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. :param dict keywords_result: (optional) A dictionary (or associative array) whose keys are the strings specified for `keywords` if both that parameter and `keywords_threshold` are specified. The value for each key is an array of matches spotted in the audio for that keyword. Each match is described by a `KeywordResult` object. A keyword for which no matches are found is omitted from the dictionary. The dictionary is omitted entirely if no matches are found for any keywords. :param list[WordAlternativeResults] word_alternatives: (optional) An array of alternative hypotheses found for words of the input audio if a `word_alternatives_threshold` is specified. """ self.final_results = final_results self.alternatives = alternatives self.keywords_result = keywords_result self.word_alternatives = word_alternatives @classmethod def _from_dict(cls, _dict): """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} if 'final' in _dict or 'final_results' in _dict: args['final_results'] = _dict.get('final') or _dict.get( 'final_results') else: raise ValueError( 'Required property \'final\' not present in SpeechRecognitionResult JSON' ) if 'alternatives' in _dict: args['alternatives'] = [ SpeechRecognitionAlternative._from_dict(x) for x in (_dict.get('alternatives')) ] else: raise ValueError( 'Required property \'alternatives\' not present in SpeechRecognitionResult JSON' ) if 'keywords_result' in _dict: args['keywords_result'] = _dict.get('keywords_result') if 'word_alternatives' in _dict: args['word_alternatives'] = [ WordAlternativeResults._from_dict(x) for x in (_dict.get('word_alternatives')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'final_results') and self.final_results is not None: _dict['final'] = self.final_results if hasattr(self, 'alternatives') and self.alternatives is not None: _dict['alternatives'] = [x._to_dict() for x in self.alternatives] if hasattr(self, 'keywords_result') and self.keywords_result is not None: _dict['keywords_result'] = self.keywords_result if hasattr(self, 'word_alternatives') and self.word_alternatives is not None: _dict['word_alternatives'] = [ x._to_dict() for x in self.word_alternatives ] return _dict def __str__(self): """Return a `str` version of this SpeechRecognitionResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SpeechRecognitionResults(object): """ SpeechRecognitionResults. :attr list[SpeechRecognitionResult] results: (optional) An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be replaced by further interim results and final results. The service periodically sends updates to the results list; the `result_index` is set to the lowest index in the array that has changed; it is incremented for new results. :attr int result_index: (optional) An index that indicates a change point in the `results` array. The service increments the index only for additional results that it sends for new audio for the same request. :attr list[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results are also requested for methods that support them, it is possible for a `SpeechRecognitionResults` object to include only the `speaker_labels` field. :attr list[str] warnings: (optional) An array of warning messages associated with the request: * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the form `"{invalid_arg_1}, {invalid_arg_2}."` * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your custom model has been built with it. Please note that this version will be supported only for a limited time. Consider updating your custom model to the new base model. If you do not do that you will be automatically switched to base model when you used the non-updated custom model."` In both cases, the request succeeds despite the warnings. """ def __init__(self, results=None, result_index=None, speaker_labels=None, warnings=None): """ Initialize a SpeechRecognitionResults object. :param list[SpeechRecognitionResult] results: (optional) An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be replaced by further interim results and final results. The service periodically sends updates to the results list; the `result_index` is set to the lowest index in the array that has changed; it is incremented for new results. :param int result_index: (optional) An index that indicates a change point in the `results` array. The service increments the index only for additional results that it sends for new audio for the same request. :param list[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results are also requested for methods that support them, it is possible for a `SpeechRecognitionResults` object to include only the `speaker_labels` field. :param list[str] warnings: (optional) An array of warning messages associated with the request: * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the form `"{invalid_arg_1}, {invalid_arg_2}."` * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your custom model has been built with it. Please note that this version will be supported only for a limited time. Consider updating your custom model to the new base model. If you do not do that you will be automatically switched to base model when you used the non-updated custom model."` In both cases, the request succeeds despite the warnings. """ self.results = results self.result_index = result_index self.speaker_labels = speaker_labels self.warnings = warnings @classmethod def _from_dict(cls, _dict): """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} if 'results' in _dict: args['results'] = [ SpeechRecognitionResult._from_dict(x) for x in (_dict.get('results')) ] if 'result_index' in _dict: args['result_index'] = _dict.get('result_index') if 'speaker_labels' in _dict: args['speaker_labels'] = [ SpeakerLabelsResult._from_dict(x) for x in (_dict.get('speaker_labels')) ] if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'result_index') and self.result_index is not None: _dict['result_index'] = self.result_index if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: _dict['speaker_labels'] = [ x._to_dict() for x in self.speaker_labels ] if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict def __str__(self): """Return a `str` version of this SpeechRecognitionResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SupportedFeatures(object): """ Describes the additional service features that are supported with the model. :attr bool custom_language_model: Indicates whether the customization interface can be used to create a custom language model based on the language model. :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. """ def __init__(self, custom_language_model, speaker_labels): """ Initialize a SupportedFeatures object. :param bool custom_language_model: Indicates whether the customization interface can be used to create a custom language model based on the language model. :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. """ self.custom_language_model = custom_language_model self.speaker_labels = speaker_labels @classmethod def _from_dict(cls, _dict): """Initialize a SupportedFeatures object from a json dictionary.""" args = {} if 'custom_language_model' in _dict: args['custom_language_model'] = _dict.get('custom_language_model') else: raise ValueError( 'Required property \'custom_language_model\' not present in SupportedFeatures JSON' ) if 'speaker_labels' in _dict: args['speaker_labels'] = _dict.get('speaker_labels') else: raise ValueError( 'Required property \'speaker_labels\' not present in SupportedFeatures JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'custom_language_model' ) and self.custom_language_model is not None: _dict['custom_language_model'] = self.custom_language_model if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: _dict['speaker_labels'] = self.speaker_labels return _dict def __str__(self): """Return a `str` version of this SupportedFeatures object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Word(object): """ Word. :attr str word: A word from the custom model's words resource. The spelling of the word is used to train the model. :attr list[str] sounds_like: An array of pronunciations for the word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes processing the word. :attr str display_as: The spelling of the word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. :attr int count: A sum of the number of times the word is found across all corpora. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before it is added by any corpora, the count begins at `1`; if the word is added from a corpus first and later modified, the count reflects only the number of times it is found in corpora. :attr list[str] source: An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string `user`. :attr list[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ def __init__(self, word, sounds_like, display_as, count, source, error=None): """ Initialize a Word object. :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. :param list[str] sounds_like: An array of pronunciations for the word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes processing the word. :param str display_as: The spelling of the word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. :param int count: A sum of the number of times the word is found across all corpora. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before it is added by any corpora, the count begins at `1`; if the word is added from a corpus first and later modified, the count reflects only the number of times it is found in corpora. :param list[str] source: An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string `user`. :param list[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ self.word = word self.sounds_like = sounds_like self.display_as = display_as self.count = count self.source = source self.error = error @classmethod def _from_dict(cls, _dict): """Initialize a Word object from a json dictionary.""" args = {} if 'word' in _dict: args['word'] = _dict.get('word') else: raise ValueError( 'Required property \'word\' not present in Word JSON') if 'sounds_like' in _dict: args['sounds_like'] = _dict.get('sounds_like') else: raise ValueError( 'Required property \'sounds_like\' not present in Word JSON') if 'display_as' in _dict: args['display_as'] = _dict.get('display_as') else: raise ValueError( 'Required property \'display_as\' not present in Word JSON') if 'count' in _dict: args['count'] = _dict.get('count') else: raise ValueError( 'Required property \'count\' not present in Word JSON') if 'source' in _dict: args['source'] = _dict.get('source') else: raise ValueError( 'Required property \'source\' not present in Word JSON') if 'error' in _dict: args['error'] = [ WordError._from_dict(x) for x in (_dict.get('error')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: _dict['display_as'] = self.display_as if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'error') and self.error is not None: _dict['error'] = [x._to_dict() for x in self.error] return _dict def __str__(self): """Return a `str` version of this Word object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WordAlternativeResult(object): """ WordAlternativeResult. :attr float confidence: A confidence score for the word alternative hypothesis in the range of 0.0 to 1.0. :attr str word: An alternative hypothesis for a word from the input audio. """ def __init__(self, confidence, word): """ Initialize a WordAlternativeResult object. :param float confidence: A confidence score for the word alternative hypothesis in the range of 0.0 to 1.0. :param str word: An alternative hypothesis for a word from the input audio. """ self.confidence = confidence self.word = word @classmethod def _from_dict(cls, _dict): """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: raise ValueError( 'Required property \'confidence\' not present in WordAlternativeResult JSON' ) if 'word' in _dict: args['word'] = _dict.get('word') else: raise ValueError( 'Required property \'word\' not present in WordAlternativeResult JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word return _dict def __str__(self): """Return a `str` version of this WordAlternativeResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WordAlternativeResults(object): """ WordAlternativeResults. :attr float start_time: The start time in seconds of the word from the input audio that corresponds to the word alternatives. :attr float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. :attr list[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ def __init__(self, start_time, end_time, alternatives): """ Initialize a WordAlternativeResults object. :param float start_time: The start time in seconds of the word from the input audio that corresponds to the word alternatives. :param float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. :param list[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ self.start_time = start_time self.end_time = end_time self.alternatives = alternatives @classmethod def _from_dict(cls, _dict): """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} if 'start_time' in _dict: args['start_time'] = _dict.get('start_time') else: raise ValueError( 'Required property \'start_time\' not present in WordAlternativeResults JSON' ) if 'end_time' in _dict: args['end_time'] = _dict.get('end_time') else: raise ValueError( 'Required property \'end_time\' not present in WordAlternativeResults JSON' ) if 'alternatives' in _dict: args['alternatives'] = [ WordAlternativeResult._from_dict(x) for x in (_dict.get('alternatives')) ] else: raise ValueError( 'Required property \'alternatives\' not present in WordAlternativeResults JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'start_time') and self.start_time is not None: _dict['start_time'] = self.start_time if hasattr(self, 'end_time') and self.end_time is not None: _dict['end_time'] = self.end_time if hasattr(self, 'alternatives') and self.alternatives is not None: _dict['alternatives'] = [x._to_dict() for x in self.alternatives] return _dict def __str__(self): """Return a `str` version of this WordAlternativeResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WordError(object): """ WordError. :attr str element: A key-value pair that describes an error associated with the definition of a word in the words resource. Each pair has the format `"element": "message"`, where `element` is the aspect of the definition that caused the problem and `message` describes the problem. The following example describes a problem with one of the word's sounds-like definitions: `"{sounds_like_string}": "Numbers are not allowed in sounds-like. You can try for example '{suggested_string}'."` You must correct the error before you can train the model. """ def __init__(self, element): """ Initialize a WordError object. :param str element: A key-value pair that describes an error associated with the definition of a word in the words resource. Each pair has the format `"element": "message"`, where `element` is the aspect of the definition that caused the problem and `message` describes the problem. The following example describes a problem with one of the word's sounds-like definitions: `"{sounds_like_string}": "Numbers are not allowed in sounds-like. You can try for example '{suggested_string}'."` You must correct the error before you can train the model. """ self.element = element @classmethod def _from_dict(cls, _dict): """Initialize a WordError object from a json dictionary.""" args = {} if 'element' in _dict: args['element'] = _dict.get('element') else: raise ValueError( 'Required property \'element\' not present in WordError JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'element') and self.element is not None: _dict['element'] = self.element return _dict def __str__(self): """Return a `str` version of this WordError object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Words(object): """ Words. :attr list[Word] words: An array of `Word` objects that provides information about each word in the custom model's words resource. The array is empty if the custom model has no words. """ def __init__(self, words): """ Initialize a Words object. :param list[Word] words: An array of `Word` objects that provides information about each word in the custom model's words resource. The array is empty if the custom model has no words. """ self.words = words @classmethod def _from_dict(cls, _dict): """Initialize a Words object from a json dictionary.""" args = {} if 'words' in _dict: args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] else: raise ValueError( 'Required property \'words\' not present in Words JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: _dict['words'] = [x._to_dict() for x in self.words] return _dict def __str__(self): """Return a `str` version of this Words object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/__init__.py0000755000076500000240000000315613451407070026531 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .watson_service import WatsonService from .watson_service import WatsonException from .watson_service import WatsonApiException from .watson_service import WatsonInvalidArgument from .authorization_v1 import AuthorizationV1 from .iam_token_manager import IAMTokenManager from .assistant_v1 import AssistantV1 from .assistant_v2 import AssistantV2 from .language_translator_v3 import LanguageTranslatorV3 from .natural_language_classifier_v1 import NaturalLanguageClassifierV1 from .natural_language_understanding_v1 import NaturalLanguageUnderstandingV1 from .personality_insights_v3 import PersonalityInsightsV3 from .text_to_speech_v1 import TextToSpeechV1 from .tone_analyzer_v3 import ToneAnalyzerV3 from .discovery_v1 import DiscoveryV1 from .compare_comply_v1 import CompareComplyV1 from .visual_recognition_v3 import VisualRecognitionV3 from .version import __version__ from .speech_to_text_v1_adapter import SpeechToTextV1Adapter as SpeechToTextV1 from .text_to_speech_adapter_v1 import TextToSpeechV1Adapter as TextToSpeechV1 watson-developer-cloud-2.10.1/watson_developer_cloud/iam_token_manager.py0000644000076500000240000001274513451407070030433 0ustar erikadsouzastaff00000000000000import requests import time DEFAULT_IAM_URL = 'https://iam.bluemix.net/identity/token' CONTENT_TYPE = 'application/x-www-form-urlencoded' ACCEPT = 'application/json' DEFAULT_AUTHORIZATION = 'Basic Yng6Yng=' REQUEST_TOKEN_GRANT_TYPE = 'urn:ibm:params:oauth:grant-type:apikey' REQUEST_TOKEN_RESPONSE_TYPE = 'cloud_iam' REFRESH_TOKEN_GRANT_TYPE = 'refresh_token' class IAMTokenManager(object): def __init__(self, iam_apikey=None, iam_access_token=None, iam_url=None): self.iam_apikey = iam_apikey self.user_access_token = iam_access_token self.iam_url = iam_url if iam_url else DEFAULT_IAM_URL self.token_info = { 'access_token': None, 'refresh_token': None, 'token_type': None, 'expires_in': None, 'expiration': None, } def request(self, method, url, headers=None, params=None, data=None, **kwargs): response = requests.request(method=method, url=url, headers=headers, params=params, data=data, **kwargs) if 200 <= response.status_code <= 299: return response.json() else: from .watson_service import WatsonApiException, get_error_message error_message = get_error_message(response) raise WatsonApiException(response.status_code, message=error_message, httpResponse=response) def get_token(self): """ The source of the token is determined by the following logic: 1. If user provides their own managed access token, assume it is valid and send it 2. If this class is managing tokens and does not yet have one, make a request for one 3. If this class is managing tokens and the token has expired refresh it. In case the refresh token is expired, get a new one If this class is managing tokens and has a valid token stored, send it """ if self.user_access_token: return self.user_access_token elif not self.token_info.get('access_token'): token_info = self._request_token() self._save_token_info(token_info) return self.token_info.get('access_token') elif self._is_token_expired(): if self._is_refresh_token_expired(): token_info = self._request_token() else: token_info = self._refresh_token() self._save_token_info(token_info) return self.token_info.get('access_token') else: return self.token_info.get('access_token') def _request_token(self): """ Request an IAM token using an API key """ headers = { 'Content-type': CONTENT_TYPE, 'Authorization': DEFAULT_AUTHORIZATION, 'accept': ACCEPT } data = { 'grant_type': REQUEST_TOKEN_GRANT_TYPE, 'apikey': self.iam_apikey, 'response_type': REQUEST_TOKEN_RESPONSE_TYPE } response = self.request( method='POST', url=self.iam_url, headers=headers, data=data) return response def _refresh_token(self): """ Refresh an IAM token using a refresh token """ headers = { 'Content-type': CONTENT_TYPE, 'Authorization': DEFAULT_AUTHORIZATION, 'accept': ACCEPT } data = { 'grant_type': REFRESH_TOKEN_GRANT_TYPE, 'refresh_token': self.token_info.get('refresh_token') } response = self.request( method='POST', url=self.iam_url, headers=headers, data=data) return response def set_access_token(self, iam_access_token): """ Set a self-managed IAM access token. The access token should be valid and not yet expired. """ self.user_access_token = iam_access_token def set_iam_apikey(self, iam_apikey): """ Set the IAM api key """ self.iam_apikey = iam_apikey def set_iam_url(self, iam_url): """ Set the IAM url """ self.iam_url = iam_url def _is_token_expired(self): """ Check if currently stored token is expired. Using a buffer to prevent the edge case of the oken expiring before the request could be made. The buffer will be a fraction of the total TTL. Using 80%. """ fraction_of_ttl = 0.8 time_to_live = self.token_info.get('expires_in') expire_time = self.token_info.get('expiration') refresh_time = expire_time - (time_to_live * (1.0 - fraction_of_ttl)) current_time = int(time.time()) return refresh_time < current_time def _is_refresh_token_expired(self): """ Used as a fail-safe to prevent the condition of a refresh token expiring, which could happen after around 30 days. This function will return true if it has been at least 7 days and 1 hour since the last token was set """ if self.token_info.get('expiration') is None: return True seven_days = 7 * 24 * 3600 current_time = int(time.time()) new_token_time = self.token_info.get('expiration') + seven_days return new_token_time < current_time def _save_token_info(self, token_info): """ Save the response from the IAM service request to the object's state. """ self.token_info = token_info watson-developer-cloud-2.10.1/watson_developer_cloud/language_translator_v3.py0000644000076500000240000011434013451412200031420 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM provided translation models that you can customize based on your unique terminology and language. Use Language Translator to take news from across the globe and present it in your language, communicate with your customers in their own language, and more. """ from __future__ import absolute_import import json from os.path import basename from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class LanguageTranslatorV3(WatsonService): """The Language Translator V3 service.""" default_url = 'https://gateway.watsonplatform.net/language-translator/api' def __init__( self, version, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Language Translator service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/language-translator/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='language_translator', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Language Translator') self.version = version ######################### # Translation ######################### def translate(self, text, model_id=None, source=None, target=None, **kwargs): """ Translate. Translates the input text from the source language to the target language. :param list[str] text: Input text in UTF-8 encoding. Multiple entries will result in multiple translations in the response. :param str model_id: A globally unique string that identifies the underlying model that is used for translation. :param str source: Translation source language code. :param str target: Translation target language code. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=language_translator;service_version=V3;operation_id=translate' params = {'version': self.version} data = { 'text': text, 'model_id': model_id, 'source': source, 'target': target } url = '/v3/translate' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Identification ######################### def identify(self, text, **kwargs): """ Identify language. Identifies the language of the input text. :param str text: Input text in UTF-8 format. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=language_translator;service_version=V3;operation_id=identify' params = {'version': self.version} data = text headers['content-type'] = 'text/plain' url = '/v3/identify' response = self.request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) return response def list_identifiable_languages(self, **kwargs): """ List identifiable languages. Lists the languages that the service can identify. Returns the language code (for example, `en` for English or `es` for Spanish) and name of each language. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=language_translator;service_version=V3;operation_id=list_identifiable_languages' params = {'version': self.version} url = '/v3/identifiable_languages' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Models ######################### def create_model(self, base_model_id, name=None, forced_glossary=None, parallel_corpus=None, forced_glossary_filename=None, parallel_corpus_filename=None, **kwargs): """ 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 maxium 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 str name: An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters. :param file forced_glossary: A TMX file with your customizations. The customizations in the file completely overwrite the domain translaton data, including high frequency or high confidence phrase translations. You can upload only one glossary with a file size less than 10 MB per call. A forced glossary should contain single words or short phrases. :param file parallel_corpus: A TMX file with parallel sentences for source and target language. You can upload multiple parallel_corpus files in one request. All uploaded parallel_corpus files combined, your parallel corpus must contain at least 5,000 parallel sentences to train successfully. :param str forced_glossary_filename: The filename for forced_glossary. :param str parallel_corpus_filename: The filename for parallel_corpus. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if base_model_id is None: raise ValueError('base_model_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=language_translator;service_version=V3;operation_id=create_model' params = { 'version': self.version, 'base_model_id': base_model_id, 'name': name } form_data = {} if forced_glossary: if not forced_glossary_filename and hasattr(forced_glossary, 'name'): forced_glossary_filename = basename(forced_glossary.name) form_data['forced_glossary'] = (forced_glossary_filename, forced_glossary, 'application/octet-stream') if parallel_corpus: if not parallel_corpus_filename and hasattr(parallel_corpus, 'name'): parallel_corpus_filename = basename(parallel_corpus.name) form_data['parallel_corpus'] = (parallel_corpus_filename, parallel_corpus, 'application/octet-stream') url = '/v3/models' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response def delete_model(self, model_id, **kwargs): """ Delete model. Deletes a custom translation model. :param str model_id: Model ID of the model to delete. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if model_id is None: raise ValueError('model_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=language_translator;service_version=V3;operation_id=delete_model' params = {'version': self.version} url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_model(self, model_id, **kwargs): """ Get model details. Gets information about a translation model, including training status for custom models. Use this API call to poll the status of your customization request. A successfully completed training will have a status of `available`. :param str model_id: Model ID of the model to get. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if model_id is None: raise ValueError('model_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=language_translator;service_version=V3;operation_id=get_model' params = {'version': self.version} url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_models(self, source=None, target=None, default_models=None, **kwargs): """ List models. Lists available translation models. :param str source: Specify a language code to filter results by source language. :param str target: Specify a language code to filter results by target language. :param bool default_models: If the default parameter isn't specified, the service will return all models (default and non-default) for each language pair. To return only default models, set this to `true`. To return only non-default models, set this to `false`. There is exactly one default model per language pair, the IBM provided base model. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=language_translator;service_version=V3;operation_id=list_models' params = { 'version': self.version, 'source': source, 'target': target, 'default': default_models } url = '/v3/models' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class DeleteModelResult(object): """ DeleteModelResult. :attr str status: "OK" indicates that the model was successfully deleted. """ def __init__(self, status): """ Initialize a DeleteModelResult object. :param str status: "OK" indicates that the model was successfully deleted. """ self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a DeleteModelResult object from a json dictionary.""" args = {} if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in DeleteModelResult JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this DeleteModelResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IdentifiableLanguage(object): """ IdentifiableLanguage. :attr str language: The language code for an identifiable language. :attr str name: The name of the identifiable language. """ def __init__(self, language, name): """ Initialize a IdentifiableLanguage object. :param str language: The language code for an identifiable language. :param str name: The name of the identifiable language. """ self.language = language self.name = name @classmethod def _from_dict(cls, _dict): """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in IdentifiableLanguage JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in IdentifiableLanguage JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name return _dict def __str__(self): """Return a `str` version of this IdentifiableLanguage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IdentifiableLanguages(object): """ IdentifiableLanguages. :attr list[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ def __init__(self, languages): """ Initialize a IdentifiableLanguages object. :param list[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ self.languages = languages @classmethod def _from_dict(cls, _dict): """Initialize a IdentifiableLanguages object from a json dictionary.""" args = {} if 'languages' in _dict: args['languages'] = [ IdentifiableLanguage._from_dict(x) for x in (_dict.get('languages')) ] else: raise ValueError( 'Required property \'languages\' not present in IdentifiableLanguages JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict def __str__(self): """Return a `str` version of this IdentifiableLanguages object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IdentifiedLanguage(object): """ IdentifiedLanguage. :attr str language: The language code for an identified language. :attr float confidence: The confidence score for the identified language. """ def __init__(self, language, confidence): """ Initialize a IdentifiedLanguage object. :param str language: The language code for an identified language. :param float confidence: The confidence score for the identified language. """ self.language = language self.confidence = confidence @classmethod def _from_dict(cls, _dict): """Initialize a IdentifiedLanguage object from a json dictionary.""" args = {} if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in IdentifiedLanguage JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: raise ValueError( 'Required property \'confidence\' not present in IdentifiedLanguage JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence return _dict def __str__(self): """Return a `str` version of this IdentifiedLanguage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IdentifiedLanguages(object): """ IdentifiedLanguages. :attr list[IdentifiedLanguage] languages: A ranking of identified languages with confidence scores. """ def __init__(self, languages): """ Initialize a IdentifiedLanguages object. :param list[IdentifiedLanguage] languages: A ranking of identified languages with confidence scores. """ self.languages = languages @classmethod def _from_dict(cls, _dict): """Initialize a IdentifiedLanguages object from a json dictionary.""" args = {} if 'languages' in _dict: args['languages'] = [ IdentifiedLanguage._from_dict(x) for x in (_dict.get('languages')) ] else: raise ValueError( 'Required property \'languages\' not present in IdentifiedLanguages JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict def __str__(self): """Return a `str` version of this IdentifiedLanguages object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Translation(object): """ Translation. :attr str translation_output: Translation output in UTF-8. """ def __init__(self, translation_output): """ Initialize a Translation object. :param str translation_output: Translation output in UTF-8. """ self.translation_output = translation_output @classmethod def _from_dict(cls, _dict): """Initialize a Translation object from a json dictionary.""" args = {} if 'translation' in _dict or 'translation_output' in _dict: args['translation_output'] = _dict.get('translation') or _dict.get( 'translation_output') else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr( self, 'translation_output') and self.translation_output is not None: _dict['translation'] = self.translation_output return _dict def __str__(self): """Return a `str` version of this Translation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TranslationModel(object): """ Response payload for models. :attr str model_id: A globally unique string that identifies the underlying model that is used for translation. :attr str name: (optional) Optional name that can be specified when the model is created. :attr str source: (optional) Translation source language code. :attr str target: (optional) Translation target language code. :attr str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be an empty string. :attr str domain: (optional) The domain of the translation model. :attr bool customizable: (optional) Whether this model can be used as a base for customization. Customized models are not further customizable, and some base models are not customizable. :attr bool default_model: (optional) Whether or not the model is a default model. A default model is the model for a given language pair that will be used when that language pair is specified in the source and target parameters. :attr str owner: (optional) Either an empty string, indicating the model is not a custom model, or the ID of the service instance that created the model. :attr str status: (optional) Availability of a model. """ def __init__(self, model_id, name=None, source=None, target=None, base_model_id=None, domain=None, customizable=None, default_model=None, owner=None, status=None): """ Initialize a TranslationModel object. :param str model_id: A globally unique string that identifies the underlying model that is used for translation. :param str name: (optional) Optional name that can be specified when the model is created. :param str source: (optional) Translation source language code. :param str target: (optional) Translation target language code. :param str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be an empty string. :param str domain: (optional) The domain of the translation model. :param bool customizable: (optional) Whether this model can be used as a base for customization. Customized models are not further customizable, and some base models are not customizable. :param bool default_model: (optional) Whether or not the model is a default model. A default model is the model for a given language pair that will be used when that language pair is specified in the source and target parameters. :param str owner: (optional) Either an empty string, indicating the model is not a custom model, or the ID of the service instance that created the model. :param str status: (optional) Availability of a model. """ self.model_id = model_id self.name = name self.source = source self.target = target self.base_model_id = base_model_id self.domain = domain self.customizable = customizable self.default_model = default_model self.owner = owner self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a TranslationModel object from a json dictionary.""" args = {} if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') else: raise ValueError( 'Required property \'model_id\' not present in TranslationModel JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') if 'source' in _dict: args['source'] = _dict.get('source') if 'target' in _dict: args['target'] = _dict.get('target') if 'base_model_id' in _dict: args['base_model_id'] = _dict.get('base_model_id') if 'domain' in _dict: args['domain'] = _dict.get('domain') if 'customizable' in _dict: args['customizable'] = _dict.get('customizable') if 'default_model' in _dict: args['default_model'] = _dict.get('default_model') if 'owner' in _dict: args['owner'] = _dict.get('owner') if 'status' in _dict: args['status'] = _dict.get('status') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'target') and self.target is not None: _dict['target'] = self.target if hasattr(self, 'base_model_id') and self.base_model_id is not None: _dict['base_model_id'] = self.base_model_id if hasattr(self, 'domain') and self.domain is not None: _dict['domain'] = self.domain if hasattr(self, 'customizable') and self.customizable is not None: _dict['customizable'] = self.customizable if hasattr(self, 'default_model') and self.default_model is not None: _dict['default_model'] = self.default_model if hasattr(self, 'owner') and self.owner is not None: _dict['owner'] = self.owner if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this TranslationModel object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TranslationModels(object): """ The response type for listing existing translation models. :attr list[TranslationModel] models: An array of available models. """ def __init__(self, models): """ Initialize a TranslationModels object. :param list[TranslationModel] models: An array of available models. """ self.models = models @classmethod def _from_dict(cls, _dict): """Initialize a TranslationModels object from a json dictionary.""" args = {} if 'models' in _dict: args['models'] = [ TranslationModel._from_dict(x) for x in (_dict.get('models')) ] else: raise ValueError( 'Required property \'models\' not present in TranslationModels JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict def __str__(self): """Return a `str` version of this TranslationModels object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TranslationResult(object): """ TranslationResult. :attr int word_count: Number of words in the input text. :attr int character_count: Number of characters in the input text. :attr list[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ def __init__(self, word_count, character_count, translations): """ Initialize a TranslationResult object. :param int word_count: Number of words in the input text. :param int character_count: Number of characters in the input text. :param list[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ self.word_count = word_count self.character_count = character_count self.translations = translations @classmethod def _from_dict(cls, _dict): """Initialize a TranslationResult object from a json dictionary.""" args = {} if 'word_count' in _dict: args['word_count'] = _dict.get('word_count') else: raise ValueError( 'Required property \'word_count\' not present in TranslationResult JSON' ) if 'character_count' in _dict: args['character_count'] = _dict.get('character_count') else: raise ValueError( 'Required property \'character_count\' not present in TranslationResult JSON' ) if 'translations' in _dict: args['translations'] = [ Translation._from_dict(x) for x in (_dict.get('translations')) ] else: raise ValueError( 'Required property \'translations\' not present in TranslationResult JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'word_count') and self.word_count is not None: _dict['word_count'] = self.word_count if hasattr(self, 'character_count') and self.character_count is not None: _dict['character_count'] = self.character_count if hasattr(self, 'translations') and self.translations is not None: _dict['translations'] = [x._to_dict() for x in self.translations] return _dict def __str__(self): """Return a `str` version of this TranslationResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/utils.py0000644000076500000240000000065013451407404026124 0ustar erikadsouzastaff00000000000000import warnings def deprecated(message): def deprecated_decorator(func): def deprecated_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn(message, category=DeprecationWarning, stacklevel=2) return func(*args, **kwargs) return deprecated_func return deprecated_decorator watson-developer-cloud-2.10.1/watson_developer_cloud/discovery_v1.py0000644000076500000240000170752413451412165027420 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The IBM Watson™ Discovery Service 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. """ from __future__ import absolute_import import json from .watson_service import datetime_to_string, string_to_datetime from os.path import basename from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class DiscoveryV1(WatsonService): """The Discovery V1 service.""" default_url = 'https://gateway.watsonplatform.net/discovery/api' def __init__( self, version, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Discovery service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/discovery/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='discovery', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Discovery') self.version = version ######################### # Environments ######################### def create_environment(self, name, description=None, size=None, **kwargs): """ Create an environment. Creates a new environment for private data. An environment must be created before collections can be created. **Note**: You can create only one environment for private data per service instance. An attempt to create another environment results in an error. :param str name: Name that identifies the environment. :param str description: Description of the environment. :param str size: Size of the environment. In the Lite plan the default and only accepted value is `LT`, in all other plans the default is `S`. :param 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') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_environment' params = {'version': self.version} data = {'name': name, 'description': description, 'size': size} url = '/v1/environments' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_environment(self, environment_id, **kwargs): """ Delete environment. :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_environment' params = {'version': self.version} url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_environment(self, environment_id, **kwargs): """ Get environment info. :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_environment' params = {'version': self.version} url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_environments(self, name=None, **kwargs): """ List environments. List existing environments for the service instance. :param str name: Show only the environment with the given name. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_environments' params = {'version': self.version, 'name': name} url = '/v1/environments' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_fields(self, environment_id, collection_ids, **kwargs): """ List fields across collections. Gets a list of the unique fields (and their types) stored in the indexes of the specified collections. :param str environment_id: The ID of the environment. :param list[str] collection_ids: A comma-separated list of collection IDs to be queried against. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_fields' params = { 'version': self.version, 'collection_ids': self._convert_list(collection_ids) } url = '/v1/environments/{0}/fields'.format( *self._encode_path_vars(environment_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_environment(self, environment_id, name=None, description=None, size=None, **kwargs): """ Update an environment. Updates an environment. The environment's **name** and **description** parameters can be changed. You must specify a **name** for the environment. :param str environment_id: The ID of the environment. :param str name: Name that identifies the environment. :param str description: Description of the environment. :param str size: Size that the environment should be increased to. Environment size cannot be modified when using a Lite plan. Environment size can only increased and not decreased. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=update_environment' params = {'version': self.version} data = {'name': name, 'description': description, 'size': size} url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) response = self.request( method='PUT', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Configurations ######################### def create_configuration(self, environment_id, name, description=None, conversions=None, enrichments=None, normalizations=None, source=None, **kwargs): """ Add configuration. Creates a new configuration. If the input configuration contains the **configuration_id**, **created**, or **updated** properties, then they are ignored and overridden by the system, and an error is not returned so that the overridden fields do not need to be removed when copying a configuration. The configuration can contain unrecognized JSON fields. Any such fields are ignored and do not generate an error. This makes it easier to use newer configuration files with older versions of the API and the service. It also makes it possible for the tooling to add additional metadata and information to the configuration. :param str environment_id: The ID of the environment. :param str name: The name of the configuration. :param str description: The description of the configuration, if available. :param Conversions conversions: Document conversion settings. :param list[Enrichment] enrichments: An array of document enrichment settings for the configuration. :param list[NormalizationOperation] normalizations: Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. :param Source source: Object containing source parameters for the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if name is None: raise ValueError('name must be provided') if conversions is not None: conversions = self._convert_model(conversions, Conversions) if enrichments is not None: enrichments = [ self._convert_model(x, Enrichment) for x in enrichments ] if normalizations is not None: normalizations = [ self._convert_model(x, NormalizationOperation) for x in normalizations ] if source is not None: source = self._convert_model(source, Source) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_configuration' params = {'version': self.version} data = { 'name': name, 'description': description, 'conversions': conversions, 'enrichments': enrichments, 'normalizations': normalizations, 'source': source } url = '/v1/environments/{0}/configurations'.format( *self._encode_path_vars(environment_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_configuration(self, environment_id, configuration_id, **kwargs): """ Delete a configuration. The deletion is performed unconditionally. A configuration deletion request succeeds even if the configuration is referenced by a collection or document ingestion. However, documents that have already been submitted for processing continue to use the deleted configuration. Documents are always processed with a snapshot of the configuration as it existed at the time the document was submitted. :param str environment_id: The ID of the environment. :param str configuration_id: The ID of the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if configuration_id is None: raise ValueError('configuration_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_configuration' params = {'version': self.version} url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_configuration(self, environment_id, configuration_id, **kwargs): """ Get configuration details. :param str environment_id: The ID of the environment. :param str configuration_id: The ID of the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if configuration_id is None: raise ValueError('configuration_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_configuration' params = {'version': self.version} url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_configurations(self, environment_id, name=None, **kwargs): """ List configurations. Lists existing configurations for the service instance. :param str environment_id: The ID of the environment. :param str name: Find configurations with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_configurations' params = {'version': self.version, 'name': name} url = '/v1/environments/{0}/configurations'.format( *self._encode_path_vars(environment_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_configuration(self, environment_id, configuration_id, name, description=None, conversions=None, enrichments=None, normalizations=None, source=None, **kwargs): """ Update a configuration. Replaces an existing configuration. * Completely replaces the original configuration. * The **configuration_id**, **updated**, and **created** fields are accepted in the request, but they are ignored, and an error is not generated. It is also acceptable for users to submit an updated configuration with none of the three properties. * Documents are processed with a snapshot of the configuration as it was at the time the document was submitted to be ingested. This means that already submitted documents will not see any updates made to the configuration. :param str environment_id: The ID of the environment. :param str configuration_id: The ID of the configuration. :param str name: The name of the configuration. :param str description: The description of the configuration, if available. :param Conversions conversions: Document conversion settings. :param list[Enrichment] enrichments: An array of document enrichment settings for the configuration. :param list[NormalizationOperation] normalizations: Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. :param Source source: Object containing source parameters for the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if configuration_id is None: raise ValueError('configuration_id must be provided') if name is None: raise ValueError('name must be provided') if conversions is not None: conversions = self._convert_model(conversions, Conversions) if enrichments is not None: enrichments = [ self._convert_model(x, Enrichment) for x in enrichments ] if normalizations is not None: normalizations = [ self._convert_model(x, NormalizationOperation) for x in normalizations ] if source is not None: source = self._convert_model(source, Source) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=update_configuration' params = {'version': self.version} data = { 'name': name, 'description': description, 'conversions': conversions, 'enrichments': enrichments, 'normalizations': normalizations, 'source': source } url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) response = self.request( method='PUT', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Test your configuration on a document ######################### def test_configuration_in_environment(self, environment_id, configuration=None, step=None, configuration_id=None, file=None, metadata=None, file_content_type=None, filename=None, **kwargs): """ Test configuration. Runs a sample document through the default or your configuration and returns diagnostic information designed to help you understand how the document was processed. The document is not added to the index. :param str environment_id: The ID of the environment. :param str configuration: The configuration to use to process the document. If this part is provided, then the provided configuration is used to process the document. If the **configuration_id** is also provided (both are present at the same time), then request is rejected. The maximum supported configuration size is 1 MB. Configuration parts larger than 1 MB are rejected. See the `GET /configurations/{configuration_id}` operation for an example configuration. :param str step: Specify to only run the input document through the given step instead of running the input document through the entire ingestion workflow. Valid values are `convert`, `enrich`, and `normalize`. :param str configuration_id: The ID of the configuration to use to process the document. If the **configuration** form part is also provided (both are present at the same time), then the request will be rejected. :param file file: The content of the document to ingest. The maximum supported file size is 50 megabytes. Files larger than 50 megabytes is rejected. :param str metadata: If you're using the Data Crawler to upload your documents, you can test a document against the type of metadata that the Data Crawler might send. The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { \"Creator\": \"Johnny Appleseed\", \"Subject\": \"Apples\" } ```. :param str file_content_type: The content type of file. :param str filename: The filename for file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=test_configuration_in_environment' params = { 'version': self.version, 'step': step, 'configuration_id': configuration_id } form_data = {} if configuration: form_data['configuration'] = (None, configuration, 'text/plain') if file: if not filename and hasattr(file, 'name'): filename = basename(file.name) if not filename: raise ValueError('filename must be provided') form_data['file'] = (filename, file, file_content_type or 'application/octet-stream') if metadata: form_data['metadata'] = (None, metadata, 'text/plain') url = '/v1/environments/{0}/preview'.format( *self._encode_path_vars(environment_id)) response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Collections ######################### def create_collection(self, environment_id, name, description=None, configuration_id=None, language=None, **kwargs): """ Create a collection. :param str environment_id: The ID of the environment. :param str name: The name of the collection to be created. :param str description: A description of the collection. :param str configuration_id: The ID of the configuration in which the collection is to be created. :param str language: The language of the documents stored in the collection, in the form of an ISO 639-1 language code. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if name is None: raise ValueError('name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_collection' params = {'version': self.version} data = { 'name': name, 'description': description, 'configuration_id': configuration_id, 'language': language } url = '/v1/environments/{0}/collections'.format( *self._encode_path_vars(environment_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_collection(self, environment_id, collection_id, **kwargs): """ Delete a collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_collection' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_collection(self, environment_id, collection_id, **kwargs): """ Get collection details. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_collection' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_collection_fields(self, environment_id, collection_id, **kwargs): """ List collection fields. Gets a list of the unique fields (and their types) stored in the index. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_collection_fields' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/fields'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_collections(self, environment_id, name=None, **kwargs): """ List collections. Lists existing collections for the service instance. :param str environment_id: The ID of the environment. :param str name: Find collections with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_collections' params = {'version': self.version, 'name': name} url = '/v1/environments/{0}/collections'.format( *self._encode_path_vars(environment_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_collection(self, environment_id, collection_id, name, description=None, configuration_id=None, **kwargs): """ Update a collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str name: The name of the collection. :param str description: A description of the collection. :param str configuration_id: The ID of the configuration in which the collection is to be updated. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=update_collection' params = {'version': self.version} data = { 'name': name, 'description': description, 'configuration_id': configuration_id } url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='PUT', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Query modifications ######################### def create_expansions(self, environment_id, collection_id, expansions, **kwargs): """ Create or update expansion list. Create or replace the Expansion list for this collection. The maximum number of expanded terms per collection is `500`. The current expansion list is replaced with the uploaded content. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param list[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all terms are expanded to all other terms in the object. Unidirectional means that a set list of terms can be expanded into a second list of terms. To create a bi-directional expansion specify an **expanded_terms** array. When found in a query, all items in the **expanded_terms** array are then expanded to the other items in the same array. To create a uni-directional expansion, specify both an array of **input_terms** and an array of **expanded_terms**. When items in the **input_terms** array are present in a query, they are expanded using the items listed in the **expanded_terms** array. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if expansions is None: raise ValueError('expansions must be provided') expansions = [self._convert_model(x, Expansion) for x in expansions] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_expansions' params = {'version': self.version} data = {'expansions': expansions} url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def create_stopword_list(self, environment_id, collection_id, stopword_file, stopword_filename=None, **kwargs): """ Create stopword list. Upload a custom stopword list to use with the specified collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param file stopword_file: The content of the stopword list to ingest. :param str stopword_filename: The filename for stopword_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if stopword_file is None: raise ValueError('stopword_file must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_stopword_list' params = {'version': self.version} form_data = {} if not stopword_filename and hasattr(stopword_file, 'name'): stopword_filename = basename(stopword_file.name) if not stopword_filename: raise ValueError('stopword_filename must be provided') form_data['stopword_file'] = (stopword_filename, stopword_file, 'application/octet-stream') url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response def create_tokenization_dictionary(self, environment_id, collection_id, tokenization_rules=None, **kwargs): """ Create tokenization dictionary. Upload a custom tokenization dictionary to use with the specified collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param list[TokenDictRule] tokenization_rules: An array of tokenization rules. Each rule contains, the original `text` string, component `tokens`, any alternate character set `readings`, and which `part_of_speech` the text is from. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if tokenization_rules is not None: tokenization_rules = [ self._convert_model(x, TokenDictRule) for x in tokenization_rules ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_tokenization_dictionary' params = {'version': self.version} data = {'tokenization_rules': tokenization_rules} url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_expansions(self, environment_id, collection_id, **kwargs): """ Delete the expansion list. Remove the expansion information for this collection. The expansion list must be deleted to disable query expansion for a collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_expansions' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def delete_stopword_list(self, environment_id, collection_id, **kwargs): """ Delete a custom stopword list. Delete a custom stopword list from the collection. After a custom stopword list is deleted, the default list is used for the collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_stopword_list' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def delete_tokenization_dictionary(self, environment_id, collection_id, **kwargs): """ Delete tokenization dictionary. Delete the tokenization dictionary from the collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_tokenization_dictionary' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_stopword_list_status(self, environment_id, collection_id, **kwargs): """ Get stopword list status. Returns the current status of the stopword list for the specified collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_stopword_list_status' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def get_tokenization_dictionary_status(self, environment_id, collection_id, **kwargs): """ Get tokenization dictionary status. Returns the current status of the tokenization dictionary for the specified collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_tokenization_dictionary_status' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_expansions(self, environment_id, collection_id, **kwargs): """ Get the expansion list. Returns the current expansion list for the specified collection. If an expansion list is not specified, an object with empty expansion arrays is returned. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_expansions' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Documents ######################### def add_document(self, environment_id, collection_id, file=None, metadata=None, file_content_type=None, filename=None, **kwargs): """ Add a document. Add a document to a collection with optional metadata. * The **version** query parameter is still required. * Returns immediately after the system has accepted the document for processing. * The user must provide document content, metadata, or both. If the request is missing both document content and metadata, it is rejected. * The user can set the **Content-Type** parameter on the **file** part to indicate the media type of the document. If the **Content-Type** parameter is missing or is one of the generic media types (for example, `application/octet-stream`), then the service attempts to automatically detect the document's media type. * The following field names are reserved and will be filtered out if present after normalization: `id`, `score`, `highlight`, and any field with the prefix of: `_`, `+`, or `-` * Fields with empty name values after normalization are filtered out before indexing. * Fields containing the following characters after normalization are filtered out before indexing: `#` and `,`. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param file file: The content of the document to ingest. The maximum supported file size is 50 megabytes. Files larger than 50 megabytes is rejected. :param str metadata: If you're using the Data Crawler to upload your documents, you can test a document against the type of metadata that the Data Crawler might send. The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { \"Creator\": \"Johnny Appleseed\", \"Subject\": \"Apples\" } ```. :param str file_content_type: The content type of file. :param str filename: The filename for file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=add_document' params = {'version': self.version} form_data = {} if file: if not filename and hasattr(file, 'name'): filename = basename(file.name) if not filename: raise ValueError('filename must be provided') form_data['file'] = (filename, file, file_content_type or 'application/octet-stream') if metadata: form_data['metadata'] = (None, metadata, 'text/plain') url = '/v1/environments/{0}/collections/{1}/documents'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response def delete_document(self, environment_id, collection_id, document_id, **kwargs): """ Delete a document. If the given document ID is invalid, or if the document is not found, then the a success response is returned (HTTP status code `200`) with the status set to 'deleted'. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_document' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_document_status(self, environment_id, collection_id, document_id, **kwargs): """ Get document details. Fetch status details about a submitted document. **Note:** this operation does not return the document itself. Instead, it returns only the document's processing status and any notices (warnings or errors) that were generated when the document was ingested. Use the query API to retrieve the actual document content. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_document_status' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_document(self, environment_id, collection_id, document_id, file=None, metadata=None, file_content_type=None, filename=None, **kwargs): """ Update a document. Replace an existing document. Starts ingesting a document with optional metadata. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. :param file file: The content of the document to ingest. The maximum supported file size is 50 megabytes. Files larger than 50 megabytes is rejected. :param str metadata: If you're using the Data Crawler to upload your documents, you can test a document against the type of metadata that the Data Crawler might send. The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { \"Creator\": \"Johnny Appleseed\", \"Subject\": \"Apples\" } ```. :param str file_content_type: The content type of file. :param str filename: The filename for file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=update_document' params = {'version': self.version} form_data = {} if file: if not filename and hasattr(file, 'name'): filename = basename(file.name) if not filename: raise ValueError('filename must be provided') form_data['file'] = (filename, file, file_content_type or 'application/octet-stream') if metadata: form_data['metadata'] = (None, metadata, 'text/plain') url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Queries ######################### def federated_query(self, environment_id, collection_ids, filter=None, query=None, natural_language_query=None, aggregation=None, count=None, return_fields=None, offset=None, sort=None, highlight=None, deduplicate=None, deduplicate_field=None, similar=None, similar_document_ids=None, similar_fields=None, passages=None, passages_fields=None, passages_count=None, passages_characters=None, bias=None, logging_opt_out=None, **kwargs): """ Long environment queries. Complex queries might be too long for a standard method query. By using this method, you can construct longer queries. However, these queries may take longer to complete than the standard method. For details, see the [Discovery service documentation](https://console.bluemix.net/docs/services/discovery/using.html). :param str environment_id: The ID of the environment. :param list[str] collection_ids: A comma-separated list of collection IDs to be queried against. :param str filter: A cacheable query that limits the documents returned to exclude any documents that don't mention the query content. Filter searches are better for metadata type searches and when you are trying to get a sense of concepts in the data set. :param str query: A query search returns all documents in your data set with full enrichments and full text, but with the most relevant documents listed first. Use a query search when you want to find the most relevant search results. You cannot use **natural_language_query** and **query** at the same time. :param str natural_language_query: A natural language query that returns relevant documents by utilizing training data and natural language understanding. You cannot use **natural_language_query** and **query** at the same time. :param str aggregation: An aggregation search uses combinations of filters and query search to return an exact answer. Aggregations are useful for building applications, because you can use them to build lists, tables, and time series. For a full list of possible aggregrations, see the Query reference. :param int count: Number of results to return. :param list[str] return_fields: A comma separated list of the portion of the document hierarchy to return. :param int offset: The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10, and the offset is 8, it returns the last two results. :param list[str] sort: A comma separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. :param bool highlight: When true a highlight field is returned for each result which contains the fields that match the query with `` tags around the matching query terms. Defaults to false. :param bool deduplicate: When `true` and used with a Watson Discovery News collection, duplicate results (based on the contents of the **title** field) are removed. Duplicate comparison is limited to the current query only; **offset** is not considered. This parameter is currently Beta functionality. :param str deduplicate_field: When specified, duplicate results based on the field specified are removed from the returned results. Duplicate comparison is limited to the current query only, **offset** is not considered. This parameter is currently Beta functionality. :param bool similar: When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. :param list[str] similar_document_ids: A comma-separated list of document IDs that will be used to find similar documents. **Note:** If the **natural_language_query** parameter is also specified, it will be used to expand the scope of the document similarity search to include the natural language query. Other query parameters, such as **filter** and **query** are subsequently applied and reduce the query scope. :param list[str] similar_fields: A comma-separated list of field names that will be used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param bool passages: A passages query that returns the most relevant passages from the results. :param list[str] passages_fields: A comma-separated list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :param int passages_count: The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. The maximum is `100`. :param int passages_characters: The approximate number of characters that any one passage will have. The default is `400`. The minimum is `50`. The maximum is `2000`. :param str bias: Field which the returned results will be biased against. The specified field must be either a **date** or **number** format. When a **date** type field is specified returned results are biased towards field values closer to the current date. When a **number** type field is specified, returned results are biased towards higher field values. This parameter cannot be used in the same query as the **sort** parameter. :param bool logging_opt_out: If `true`, queries are not stored in the Discovery **Logs** endpoint. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {'X-Watson-Logging-Opt-Out': logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=federated_query' params = {'version': self.version} data = { 'collection_ids': self._convert_list(collection_ids), 'filter': filter, 'query': query, 'natural_language_query': natural_language_query, 'aggregation': aggregation, 'count': count, 'return': self._convert_list(return_fields), 'offset': offset, 'sort': self._convert_list(sort), 'highlight': highlight, 'deduplicate': deduplicate, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': self._convert_list(similar_document_ids), 'similar.fields': self._convert_list(similar_fields), 'passages': passages, 'passages.fields': self._convert_list(passages_fields), 'passages.count': passages_count, 'passages.characters': passages_characters, 'bias': bias } url = '/v1/environments/{0}/query'.format( *self._encode_path_vars(environment_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def federated_query_notices(self, environment_id, collection_ids, filter=None, query=None, natural_language_query=None, aggregation=None, count=None, return_fields=None, offset=None, sort=None, highlight=None, deduplicate_field=None, similar=None, similar_document_ids=None, similar_fields=None, **kwargs): """ Query multiple collection system notices. Queries for notices (errors or warnings) that might have been generated by the system. Notices are generated when ingesting documents and performing relevance training. See the [Discovery service documentation](https://console.bluemix.net/docs/services/discovery/using.html) for more details on the query language. :param str environment_id: The ID of the environment. :param list[str] collection_ids: A comma-separated list of collection IDs to be queried against. :param str filter: A cacheable query that excludes documents that don't mention the query content. Filter searches are better for metadata-type searches and for assessing the concepts in the data set. :param str query: A query search returns all documents in your data set with full enrichments and full text, but with the most relevant documents listed first. Use a query search when you want to find the most relevant search results. You cannot use **natural_language_query** and **query** at the same time. :param str natural_language_query: A natural language query that returns relevant documents by utilizing training data and natural language understanding. You cannot use **natural_language_query** and **query** at the same time. :param str aggregation: An aggregation search that returns an exact answer by combining query search with filters. Useful for applications to build lists, tables, and time series. For a full list of possible aggregations, see the Query reference. :param int count: Number of results to return. :param list[str] return_fields: A comma-separated list of the portion of the document hierarchy to return. :param int offset: The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. :param list[str] sort: A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. :param bool highlight: When true, a highlight field is returned for each result which contains the fields which match the query with `` tags around the matching query terms. :param str deduplicate_field: When specified, duplicate results based on the field specified are removed from the returned results. Duplicate comparison is limited to the current query only, **offset** is not considered. This parameter is currently Beta functionality. :param bool similar: When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. :param list[str] similar_document_ids: A comma-separated list of document IDs to find similar documents. **Tip:** Include the **natural_language_query** parameter to expand the scope of the document similarity search with the natural language query. Other query parameters, such as **filter** and **query**, are subsequently applied and reduce the scope. :param list[str] similar_fields: A comma-separated list of field names that are used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=federated_query_notices' params = { 'version': self.version, 'collection_ids': self._convert_list(collection_ids), 'filter': filter, 'query': query, 'natural_language_query': natural_language_query, 'aggregation': aggregation, 'count': count, 'return': self._convert_list(return_fields), 'offset': offset, 'sort': self._convert_list(sort), 'highlight': highlight, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': self._convert_list(similar_document_ids), 'similar.fields': self._convert_list(similar_fields) } url = '/v1/environments/{0}/notices'.format( *self._encode_path_vars(environment_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def query(self, environment_id, collection_id, filter=None, query=None, natural_language_query=None, passages=None, aggregation=None, count=None, return_fields=None, offset=None, sort=None, highlight=None, passages_fields=None, passages_count=None, passages_characters=None, deduplicate=None, deduplicate_field=None, similar=None, similar_document_ids=None, similar_fields=None, logging_opt_out=None, collection_ids=None, bias=None, **kwargs): """ Long collection queries. Complex queries might be too long for a standard method query. By using this method, you can construct longer queries. However, these queries may take longer to complete than the standard method. For details, see the [Discovery service documentation](https://console.bluemix.net/docs/services/discovery/using.html). :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str filter: A cacheable query that limits the documents returned to exclude any documents that don't mention the query content. Filter searches are better for metadata type searches and when you are trying to get a sense of concepts in the data set. :param str query: A query search returns all documents in your data set with full enrichments and full text, but with the most relevant documents listed first. Use a query search when you want to find the most relevant search results. You cannot use **natural_language_query** and **query** at the same time. :param str natural_language_query: A natural language query that returns relevant documents by utilizing training data and natural language understanding. You cannot use **natural_language_query** and **query** at the same time. :param bool passages: A passages query that returns the most relevant passages from the results. :param str aggregation: An aggregation search uses combinations of filters and query search to return an exact answer. Aggregations are useful for building applications, because you can use them to build lists, tables, and time series. For a full list of possible aggregrations, see the Query reference. :param int count: Number of results to return. :param list[str] return_fields: A comma separated list of the portion of the document hierarchy to return. :param int offset: The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10, and the offset is 8, it returns the last two results. :param list[str] sort: A comma separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. :param bool highlight: When true a highlight field is returned for each result which contains the fields that match the query with `` tags around the matching query terms. Defaults to false. :param list[str] passages_fields: A comma-separated list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :param int passages_count: The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. The maximum is `100`. :param int passages_characters: The approximate number of characters that any one passage will have. The default is `400`. The minimum is `50`. The maximum is `2000`. :param bool deduplicate: When `true` and used with a Watson Discovery News collection, duplicate results (based on the contents of the **title** field) are removed. Duplicate comparison is limited to the current query only; **offset** is not considered. This parameter is currently Beta functionality. :param str deduplicate_field: When specified, duplicate results based on the field specified are removed from the returned results. Duplicate comparison is limited to the current query only, **offset** is not considered. This parameter is currently Beta functionality. :param bool similar: When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. :param list[str] similar_document_ids: A comma-separated list of document IDs that will be used to find similar documents. **Note:** If the **natural_language_query** parameter is also specified, it will be used to expand the scope of the document similarity search to include the natural language query. Other query parameters, such as **filter** and **query** are subsequently applied and reduce the query scope. :param list[str] similar_fields: A comma-separated list of field names that will be used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param bool logging_opt_out: If `true`, queries are not stored in the Discovery **Logs** endpoint. :param str collection_ids: A comma-separated list of collection IDs to be queried against. Required when querying multiple collections, invalid when performing a single collection query. :param str bias: Field which the returned results will be biased against. The specified field must be either a **date** or **number** format. When a **date** type field is specified returned results are biased towards field values closer to the current date. When a **number** type field is specified, returned results are biased towards higher field values. This parameter cannot be used in the same query as the **sort** parameter. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {'X-Watson-Logging-Opt-Out': logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=query' params = {'version': self.version} data = { 'version': self.version, 'filter': filter, 'query': query, 'natural_language_query': natural_language_query, 'passages': passages, 'aggregation': aggregation, 'count': count, 'return': self._convert_list(return_fields), 'offset': offset, 'sort': self._convert_list(sort), 'highlight': highlight, 'passages.fields': self._convert_list(passages_fields), 'passages.count': passages_count, 'passages.characters': passages_characters, 'deduplicate': deduplicate, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': self._convert_list(similar_document_ids), 'similar.fields': self._convert_list(similar_fields), 'collection_ids': collection_ids, 'bias': bias } url = '/v1/environments/{0}/collections/{1}/query'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def query_entities(self, environment_id, collection_id, feature=None, entity=None, context=None, count=None, evidence_count=None, **kwargs): """ Knowledge Graph entity query. See the [Knowledge Graph documentation](https://console.bluemix.net/docs/services/discovery/building-kg.html) for more details. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str feature: The entity query feature to perform. Supported features are `disambiguate` and `similar_entities`. :param QueryEntitiesEntity entity: A text string that appears within the entity text field. :param QueryEntitiesContext context: Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`. :param int count: The number of results to return. The default is `10`. The maximum is `1000`. :param int evidence_count: The number of evidence items to return for each result. The default is `0`. The maximum number of evidence items per query is 10,000. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if entity is not None: entity = self._convert_model(entity, QueryEntitiesEntity) if context is not None: context = self._convert_model(context, QueryEntitiesContext) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=query_entities' params = {'version': self.version} data = { 'feature': feature, 'entity': entity, 'context': context, 'count': count, 'evidence_count': evidence_count } url = '/v1/environments/{0}/collections/{1}/query_entities'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def query_notices(self, environment_id, collection_id, filter=None, query=None, natural_language_query=None, passages=None, aggregation=None, count=None, return_fields=None, offset=None, sort=None, highlight=None, passages_fields=None, passages_count=None, passages_characters=None, deduplicate_field=None, similar=None, similar_document_ids=None, similar_fields=None, **kwargs): """ Query system notices. Queries for notices (errors or warnings) that might have been generated by the system. Notices are generated when ingesting documents and performing relevance training. See the [Discovery service documentation](https://console.bluemix.net/docs/services/discovery/using.html) for more details on the query language. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str filter: A cacheable query that excludes documents that don't mention the query content. Filter searches are better for metadata-type searches and for assessing the concepts in the data set. :param str query: A query search returns all documents in your data set with full enrichments and full text, but with the most relevant documents listed first. Use a query search when you want to find the most relevant search results. You cannot use **natural_language_query** and **query** at the same time. :param str natural_language_query: A natural language query that returns relevant documents by utilizing training data and natural language understanding. You cannot use **natural_language_query** and **query** at the same time. :param bool passages: A passages query that returns the most relevant passages from the results. :param str aggregation: An aggregation search that returns an exact answer by combining query search with filters. Useful for applications to build lists, tables, and time series. For a full list of possible aggregations, see the Query reference. :param int count: Number of results to return. :param list[str] return_fields: A comma-separated list of the portion of the document hierarchy to return. :param int offset: The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. :param list[str] sort: A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. :param bool highlight: When true, a highlight field is returned for each result which contains the fields which match the query with `` tags around the matching query terms. :param list[str] passages_fields: A comma-separated list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :param int passages_count: The maximum number of passages to return. The search returns fewer passages if the requested total is not found. :param int passages_characters: The approximate number of characters that any one passage will have. :param str deduplicate_field: When specified, duplicate results based on the field specified are removed from the returned results. Duplicate comparison is limited to the current query only, **offset** is not considered. This parameter is currently Beta functionality. :param bool similar: When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. :param list[str] similar_document_ids: A comma-separated list of document IDs to find similar documents. **Tip:** Include the **natural_language_query** parameter to expand the scope of the document similarity search with the natural language query. Other query parameters, such as **filter** and **query**, are subsequently applied and reduce the scope. :param list[str] similar_fields: A comma-separated list of field names that are used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=query_notices' params = { 'version': self.version, 'filter': filter, 'query': query, 'natural_language_query': natural_language_query, 'passages': passages, 'aggregation': aggregation, 'count': count, 'return': self._convert_list(return_fields), 'offset': offset, 'sort': self._convert_list(sort), 'highlight': highlight, 'passages.fields': self._convert_list(passages_fields), 'passages.count': passages_count, 'passages.characters': passages_characters, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': self._convert_list(similar_document_ids), 'similar.fields': self._convert_list(similar_fields) } url = '/v1/environments/{0}/collections/{1}/notices'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def query_relations(self, environment_id, collection_id, entities=None, context=None, sort=None, filter=None, count=None, evidence_count=None, **kwargs): """ Knowledge Graph relationship query. See the [Knowledge Graph documentation](https://console.bluemix.net/docs/services/discovery/building-kg.html) for more details. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param list[QueryRelationsEntity] entities: An array of entities to find relationships for. :param QueryEntitiesContext context: Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`. :param str sort: The sorting method for the relationships, can be `score` or `frequency`. `frequency` is the number of unique times each entity is identified. The default is `score`. This parameter cannot be used in the same query as the **bias** parameter. :param QueryRelationsFilter filter: Filters to apply to the relationship query. :param int count: The number of results to return. The default is `10`. The maximum is `1000`. :param int evidence_count: The number of evidence items to return for each result. The default is `0`. The maximum number of evidence items per query is 10,000. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if entities is not None: entities = [ self._convert_model(x, QueryRelationsEntity) for x in entities ] if context is not None: context = self._convert_model(context, QueryEntitiesContext) if filter is not None: filter = self._convert_model(filter, QueryRelationsFilter) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=query_relations' params = {'version': self.version} data = { 'entities': entities, 'context': context, 'sort': sort, 'filter': filter, 'count': count, 'evidence_count': evidence_count } url = '/v1/environments/{0}/collections/{1}/query_relations'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Training data ######################### def add_training_data(self, environment_id, collection_id, natural_language_query=None, filter=None, examples=None, **kwargs): """ Add query to training data. Adds a query to the training data for this collection. The query can contain a filter and natural language query. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str natural_language_query: :param str filter: :param list[TrainingExample] examples: :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if examples is not None: examples = [ self._convert_model(x, TrainingExample) for x in examples ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=add_training_data' params = {'version': self.version} data = { 'natural_language_query': natural_language_query, 'filter': filter, 'examples': examples } url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def create_training_example(self, environment_id, collection_id, query_id, document_id=None, cross_reference=None, relevance=None, **kwargs): """ Add example to training data query. Adds a example to this training data query. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param str document_id: :param str cross_reference: :param int relevance: :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_training_example' params = {'version': self.version} data = { 'document_id': document_id, 'cross_reference': cross_reference, 'relevance': relevance } url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_all_training_data(self, environment_id, collection_id, **kwargs): """ Delete all training data. Deletes all training data from a collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_all_training_data' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def delete_training_data(self, environment_id, collection_id, query_id, **kwargs): """ Delete a training data query. Removes the training data query and all associated examples from the training data set. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_training_data' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def delete_training_example(self, environment_id, collection_id, query_id, example_id, **kwargs): """ Delete example for training data query. Deletes the example document with the given ID from the training data query. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param str example_id: The ID of the document as it is indexed. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_id must be provided') if example_id is None: raise ValueError('example_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_training_example' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_training_data(self, environment_id, collection_id, query_id, **kwargs): """ Get details about a query. Gets details for a specific training data query, including the query string and all examples. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_training_data' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def get_training_example(self, environment_id, collection_id, query_id, example_id, **kwargs): """ Get details for training data example. Gets the details for this training example. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param str example_id: The ID of the document as it is indexed. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_id must be provided') if example_id is None: raise ValueError('example_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_training_example' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_training_data(self, environment_id, collection_id, **kwargs): """ List training data. Lists the training data for the specified collection. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_training_data' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_training_examples(self, environment_id, collection_id, query_id, **kwargs): """ List examples for a training data query. List all examples for this training data query. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_training_examples' params = {'version': self.version} url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_training_example(self, environment_id, collection_id, query_id, example_id, cross_reference=None, relevance=None, **kwargs): """ Change label or cross reference for example. Changes the label or cross reference query for this training data example. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param str example_id: The ID of the document as it is indexed. :param str cross_reference: :param int relevance: :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_id must be provided') if example_id is None: raise ValueError('example_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=update_training_example' params = {'version': self.version} data = {'cross_reference': cross_reference, 'relevance': relevance} url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) response = self.request( method='PUT', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # User data ######################### def delete_user_data(self, customer_id, **kwargs): """ Delete labeled data. Deletes all data associated with a specified customer ID. The method has no effect if no data is associated with the customer ID. You associate a customer ID with data by passing the **X-Watson-Metadata** header with a request that passes data. For more information about personal data and customer IDs, see [Information security](https://console.bluemix.net/docs/services/discovery/information-security.html). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_user_data' params = {'version': self.version, 'customer_id': customer_id} url = '/v1/user_data' response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Events and feedback ######################### def create_event(self, type, data, **kwargs): """ Create event. The **Events** API can be used to create log entries that are associated with specific queries. For example, you can record which documents in the results set were \"clicked\" by a user and when that click occured. :param str type: The event type to be created. :param EventData data: Query event data object. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if type is None: raise ValueError('type must be provided') if data is None: raise ValueError('data must be provided') data = self._convert_model(data, EventData) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_event' params = {'version': self.version} data = {'type': type, 'data': data} url = '/v1/events' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def get_metrics_event_rate(self, start_time=None, end_time=None, result_type=None, **kwargs): """ Percentage of queries with an associated event. The percentage of queries using the **natural_language_query** parameter that have a corresponding \"click\" event over a specified time window. This metric requires having integrated event tracking in your application using the **Events** API. :param datetime start_time: Metric is computed from data recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param datetime end_time: Metric is computed from data recorded before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param str result_type: The type of result to consider when calculating the metric. :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_metrics_event_rate' params = { 'version': self.version, 'start_time': start_time, 'end_time': end_time, 'result_type': result_type } url = '/v1/metrics/event_rate' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def get_metrics_query(self, start_time=None, end_time=None, result_type=None, **kwargs): """ Number of queries over time. Total number of queries using the **natural_language_query** parameter over a specific time window. :param datetime start_time: Metric is computed from data recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param datetime end_time: Metric is computed from data recorded before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param str result_type: The type of result to consider when calculating the metric. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_metrics_query' params = { 'version': self.version, 'start_time': start_time, 'end_time': end_time, 'result_type': result_type } url = '/v1/metrics/number_of_queries' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def get_metrics_query_event(self, start_time=None, end_time=None, result_type=None, **kwargs): """ Number of queries with an event over time. Total number of queries using the **natural_language_query** parameter that have a corresponding \"click\" event over a specified time window. This metric requires having integrated event tracking in your application using the **Events** API. :param datetime start_time: Metric is computed from data recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param datetime end_time: Metric is computed from data recorded before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param str result_type: The type of result to consider when calculating the metric. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_metrics_query_event' params = { 'version': self.version, 'start_time': start_time, 'end_time': end_time, 'result_type': result_type } url = '/v1/metrics/number_of_queries_with_event' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def get_metrics_query_no_results(self, start_time=None, end_time=None, result_type=None, **kwargs): """ Number of queries with no search results over time. Total number of queries using the **natural_language_query** parameter that have no results returned over a specified time window. :param datetime start_time: Metric is computed from data recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param datetime end_time: Metric is computed from data recorded before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. :param str result_type: The type of result to consider when calculating the metric. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_metrics_query_no_results' params = { 'version': self.version, 'start_time': start_time, 'end_time': end_time, 'result_type': result_type } url = '/v1/metrics/number_of_queries_with_no_search_results' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def get_metrics_query_token_event(self, count=None, **kwargs): """ Most frequent query tokens with an event. The most frequent query tokens parsed from the **natural_language_query** parameter and their corresponding \"click\" event rate within the recording period (queries and events are stored for 30 days). A query token is an individual word or unigram within the query string. :param int count: Number of results to return. :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_metrics_query_token_event' params = {'version': self.version, 'count': count} url = '/v1/metrics/top_query_tokens_with_event_rate' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def query_log(self, filter=None, query=None, count=None, offset=None, sort=None, **kwargs): """ Search the query and event log. Searches the query and event log to find query sessions that match the specified criteria. Searching the **logs** endpoint uses the standard Discovery query syntax for the parameters that are supported. :param str filter: A cacheable query that excludes documents that don't mention the query content. Filter searches are better for metadata-type searches and for assessing the concepts in the data set. :param str query: A query search returns all documents in your data set with full enrichments and full text, but with the most relevant documents listed first. Use a query search when you want to find the most relevant search results. You cannot use **natural_language_query** and **query** at the same time. :param int count: Number of results to return. :param int offset: The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. :param list[str] sort: A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=query_log' params = { 'version': self.version, 'filter': filter, 'query': query, 'count': count, 'offset': offset, 'sort': self._convert_list(sort) } url = '/v1/logs' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Credentials ######################### def create_credentials(self, environment_id, source_type=None, credential_details=None, **kwargs): """ Create credentials. Creates a set of credentials to connect to a remote source. Created credentials are used in a configuration to associate a collection with the remote source. **Note:** All credentials are sent over an encrypted connection and encrypted at rest. :param str environment_id: The ID of the environment. :param str source_type: The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of Enterprise Box. - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. :param CredentialDetails credential_details: Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if credential_details is not None: credential_details = self._convert_model(credential_details, CredentialDetails) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_credentials' params = {'version': self.version} data = { 'source_type': source_type, 'credential_details': credential_details } url = '/v1/environments/{0}/credentials'.format( *self._encode_path_vars(environment_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_credentials(self, environment_id, credential_id, **kwargs): """ Delete credentials. Deletes a set of stored credentials from your Discovery instance. :param str environment_id: The ID of the environment. :param str credential_id: The unique identifier for a set of source credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if credential_id is None: raise ValueError('credential_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_credentials' params = {'version': self.version} url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_credentials(self, environment_id, credential_id, **kwargs): """ View Credentials. Returns details about the specified credentials. **Note:** Secure credential information such as a password or SSH key is never returned and must be obtained from the source system. :param str environment_id: The ID of the environment. :param str credential_id: The unique identifier for a set of source credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if credential_id is None: raise ValueError('credential_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_credentials' params = {'version': self.version} url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_credentials(self, environment_id, **kwargs): """ List credentials. List all the source credentials that have been created for this service instance. **Note:** All credentials are sent over an encrypted connection and encrypted at rest. :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_credentials' params = {'version': self.version} url = '/v1/environments/{0}/credentials'.format( *self._encode_path_vars(environment_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_credentials(self, environment_id, credential_id, source_type=None, credential_details=None, **kwargs): """ Update credentials. Updates an existing set of source credentials. **Note:** All credentials are sent over an encrypted connection and encrypted at rest. :param str environment_id: The ID of the environment. :param str credential_id: The unique identifier for a set of source credentials. :param str source_type: The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of Enterprise Box. - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. :param CredentialDetails credential_details: Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if credential_id is None: raise ValueError('credential_id must be provided') if credential_details is not None: credential_details = self._convert_model(credential_details, CredentialDetails) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=update_credentials' params = {'version': self.version} data = { 'source_type': source_type, 'credential_details': credential_details } url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) response = self.request( method='PUT', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # gatewayConfiguration ######################### def create_gateway(self, environment_id, name=None, **kwargs): """ Create Gateway. Create a gateway configuration to use with a remotely installed gateway. :param str environment_id: The ID of the environment. :param str name: User-defined name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=create_gateway' params = {'version': self.version} data = {'name': name} url = '/v1/environments/{0}/gateways'.format( *self._encode_path_vars(environment_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_gateway(self, environment_id, gateway_id, **kwargs): """ Delete Gateway. Delete the specified gateway configuration. :param str environment_id: The ID of the environment. :param str gateway_id: The requested gateway ID. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if gateway_id is None: raise ValueError('gateway_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=delete_gateway' params = {'version': self.version} url = '/v1/environments/{0}/gateways/{1}'.format( *self._encode_path_vars(environment_id, gateway_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_gateway(self, environment_id, gateway_id, **kwargs): """ List Gateway Details. List information about the specified gateway. :param str environment_id: The ID of the environment. :param str gateway_id: The requested gateway ID. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') if gateway_id is None: raise ValueError('gateway_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=get_gateway' params = {'version': self.version} url = '/v1/environments/{0}/gateways/{1}'.format( *self._encode_path_vars(environment_id, gateway_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_gateways(self, environment_id, **kwargs): """ List Gateways. List the currently configured gateways. :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if environment_id is None: raise ValueError('environment_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=discovery;service_version=V1;operation_id=list_gateways' params = {'version': self.version} url = '/v1/environments/{0}/gateways'.format( *self._encode_path_vars(environment_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class AggregationResult(object): """ AggregationResult. :attr str key: (optional) Key that matched the aggregation type. :attr int matching_results: (optional) Number of matching results. :attr list[QueryAggregation] aggregations: (optional) Aggregations returned in the case of chained aggregations. """ def __init__(self, key=None, matching_results=None, aggregations=None): """ Initialize a AggregationResult object. :param str key: (optional) Key that matched the aggregation type. :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned in the case of chained aggregations. """ self.key = key self.matching_results = matching_results self.aggregations = aggregations @classmethod def _from_dict(cls, _dict): """Initialize a AggregationResult object from a json dictionary.""" args = {} if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation._from_dict(x) for x in (_dict.get('aggregations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: _dict['key'] = self.key if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict def __str__(self): """Return a `str` version of this AggregationResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Collection(object): """ A collection for storing documents. :attr str collection_id: (optional) The unique identifier of the collection. :attr str name: (optional) The name of the collection. :attr str description: (optional) The description of the collection. :attr datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. :attr datetime updated: (optional) The timestamp of when the collection was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str status: (optional) The status of the collection. :attr str configuration_id: (optional) The unique identifier of the collection's configuration. :attr str language: (optional) The language of the documents stored in the collection. Permitted values include `en` (English), `de` (German), and `es` (Spanish). :attr DocumentCounts document_counts: (optional) The object providing information about the documents in the collection. Present only when retrieving details of a collection. :attr CollectionDiskUsage disk_usage: (optional) Summary of the disk usage statistics for this collection. :attr TrainingStatus training_status: (optional) Provides information about the status of relevance training for collection. :attr SourceStatus source_crawl: (optional) Object containing source crawl status information. """ def __init__(self, collection_id=None, name=None, description=None, created=None, updated=None, status=None, configuration_id=None, language=None, document_counts=None, disk_usage=None, training_status=None, source_crawl=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. :param str description: (optional) The description of the collection. :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. :param datetime updated: (optional) The timestamp of when the collection was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str status: (optional) The status of the collection. :param str configuration_id: (optional) The unique identifier of the collection's configuration. :param str language: (optional) The language of the documents stored in the collection. Permitted values include `en` (English), `de` (German), and `es` (Spanish). :param DocumentCounts document_counts: (optional) The object providing information about the documents in the collection. Present only when retrieving details of a collection. :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage statistics for this collection. :param TrainingStatus training_status: (optional) Provides information about the status of relevance training for collection. :param SourceStatus source_crawl: (optional) Object containing source crawl status information. """ self.collection_id = collection_id self.name = name self.description = description self.created = created self.updated = updated self.status = status self.configuration_id = configuration_id self.language = language self.document_counts = document_counts self.disk_usage = disk_usage self.training_status = training_status self.source_crawl = source_crawl @classmethod def _from_dict(cls, _dict): """Initialize a Collection object from a json dictionary.""" args = {} if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'name' in _dict: args['name'] = _dict.get('name') if 'description' in _dict: args['description'] = _dict.get('description') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'status' in _dict: args['status'] = _dict.get('status') if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') if 'language' in _dict: args['language'] = _dict.get('language') if 'document_counts' in _dict: args['document_counts'] = DocumentCounts._from_dict( _dict.get('document_counts')) if 'disk_usage' in _dict: args['disk_usage'] = CollectionDiskUsage._from_dict( _dict.get('disk_usage')) if 'training_status' in _dict: args['training_status'] = TrainingStatus._from_dict( _dict.get('training_status')) if 'source_crawl' in _dict: args['source_crawl'] = SourceStatus._from_dict( _dict.get('source_crawl')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'configuration_id') and self.configuration_id is not None: _dict['configuration_id'] = self.configuration_id if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'document_counts') and self.document_counts is not None: _dict['document_counts'] = self.document_counts._to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: _dict['disk_usage'] = self.disk_usage._to_dict() if hasattr(self, 'training_status') and self.training_status is not None: _dict['training_status'] = self.training_status._to_dict() if hasattr(self, 'source_crawl') and self.source_crawl is not None: _dict['source_crawl'] = self.source_crawl._to_dict() return _dict def __str__(self): """Return a `str` version of this Collection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CollectionDiskUsage(object): """ Summary of the disk usage statistics for this collection. :attr int used_bytes: (optional) Number of bytes used by the collection. """ def __init__(self, used_bytes=None): """ Initialize a CollectionDiskUsage object. :param int used_bytes: (optional) Number of bytes used by the collection. """ self.used_bytes = used_bytes @classmethod def _from_dict(cls, _dict): """Initialize a CollectionDiskUsage object from a json dictionary.""" args = {} if 'used_bytes' in _dict: args['used_bytes'] = _dict.get('used_bytes') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'used_bytes') and self.used_bytes is not None: _dict['used_bytes'] = self.used_bytes return _dict def __str__(self): """Return a `str` version of this CollectionDiskUsage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CollectionUsage(object): """ Summary of the collection usage in the environment. :attr int available: (optional) Number of active collections in the environment. :attr int maximum_allowed: (optional) Total number of collections allowed in the environment. """ def __init__(self, available=None, maximum_allowed=None): """ Initialize a CollectionUsage object. :param int available: (optional) Number of active collections in the environment. :param int maximum_allowed: (optional) Total number of collections allowed in the environment. """ self.available = available self.maximum_allowed = maximum_allowed @classmethod def _from_dict(cls, _dict): """Initialize a CollectionUsage object from a json dictionary.""" args = {} if 'available' in _dict: args['available'] = _dict.get('available') if 'maximum_allowed' in _dict: args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'available') and self.available is not None: _dict['available'] = self.available if hasattr(self, 'maximum_allowed') and self.maximum_allowed is not None: _dict['maximum_allowed'] = self.maximum_allowed return _dict def __str__(self): """Return a `str` version of this CollectionUsage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Configuration(object): """ A custom configuration for the environment. :attr str configuration_id: (optional) The unique identifier of the configuration. :attr str name: The name of the configuration. :attr datetime created: (optional) The creation date of the configuration in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr datetime updated: (optional) The timestamp of when the configuration was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str description: (optional) The description of the configuration, if available. :attr Conversions conversions: (optional) Document conversion settings. :attr list[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. :attr list[NormalizationOperation] normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. :attr Source source: (optional) Object containing source parameters for the configuration. """ def __init__(self, name, configuration_id=None, created=None, updated=None, description=None, conversions=None, enrichments=None, normalizations=None, source=None): """ Initialize a Configuration object. :param str name: The name of the configuration. :param str configuration_id: (optional) The unique identifier of the configuration. :param datetime created: (optional) The creation date of the configuration in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param datetime updated: (optional) The timestamp of when the configuration was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. :param list[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. :param list[NormalizationOperation] normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. :param Source source: (optional) Object containing source parameters for the configuration. """ self.configuration_id = configuration_id self.name = name self.created = created self.updated = updated self.description = description self.conversions = conversions self.enrichments = enrichments self.normalizations = normalizations self.source = source @classmethod def _from_dict(cls, _dict): """Initialize a Configuration object from a json dictionary.""" args = {} if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Configuration JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'description' in _dict: args['description'] = _dict.get('description') if 'conversions' in _dict: args['conversions'] = Conversions._from_dict( _dict.get('conversions')) if 'enrichments' in _dict: args['enrichments'] = [ Enrichment._from_dict(x) for x in (_dict.get('enrichments')) ] if 'normalizations' in _dict: args['normalizations'] = [ NormalizationOperation._from_dict(x) for x in (_dict.get('normalizations')) ] if 'source' in _dict: args['source'] = Source._from_dict(_dict.get('source')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configuration_id') and self.configuration_id is not None: _dict['configuration_id'] = self.configuration_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'conversions') and self.conversions is not None: _dict['conversions'] = self.conversions._to_dict() if hasattr(self, 'enrichments') and self.enrichments is not None: _dict['enrichments'] = [x._to_dict() for x in self.enrichments] if hasattr(self, 'normalizations') and self.normalizations is not None: _dict['normalizations'] = [ x._to_dict() for x in self.normalizations ] if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source._to_dict() return _dict def __str__(self): """Return a `str` version of this Configuration object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Conversions(object): """ Document conversion settings. :attr PdfSettings pdf: (optional) A list of PDF conversion settings. :attr WordSettings word: (optional) A list of Word conversion settings. :attr HtmlSettings html: (optional) A list of HTML conversion settings. :attr SegmentSettings segment: (optional) A list of Document Segmentation settings. :attr list[NormalizationOperation] json_normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. """ def __init__(self, pdf=None, word=None, html=None, segment=None, json_normalizations=None): """ Initialize a Conversions object. :param PdfSettings pdf: (optional) A list of PDF conversion settings. :param WordSettings word: (optional) A list of Word conversion settings. :param HtmlSettings html: (optional) A list of HTML conversion settings. :param SegmentSettings segment: (optional) A list of Document Segmentation settings. :param list[NormalizationOperation] json_normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. """ self.pdf = pdf self.word = word self.html = html self.segment = segment self.json_normalizations = json_normalizations @classmethod def _from_dict(cls, _dict): """Initialize a Conversions object from a json dictionary.""" args = {} if 'pdf' in _dict: args['pdf'] = PdfSettings._from_dict(_dict.get('pdf')) if 'word' in _dict: args['word'] = WordSettings._from_dict(_dict.get('word')) if 'html' in _dict: args['html'] = HtmlSettings._from_dict(_dict.get('html')) if 'segment' in _dict: args['segment'] = SegmentSettings._from_dict(_dict.get('segment')) if 'json_normalizations' in _dict: args['json_normalizations'] = [ NormalizationOperation._from_dict(x) for x in (_dict.get('json_normalizations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pdf') and self.pdf is not None: _dict['pdf'] = self.pdf._to_dict() if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word._to_dict() if hasattr(self, 'html') and self.html is not None: _dict['html'] = self.html._to_dict() if hasattr(self, 'segment') and self.segment is not None: _dict['segment'] = self.segment._to_dict() if hasattr( self, 'json_normalizations') and self.json_normalizations is not None: _dict['json_normalizations'] = [ x._to_dict() for x in self.json_normalizations ] return _dict def __str__(self): """Return a `str` version of this Conversions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CreateEventResponse(object): """ An object defining the event being created. :attr str type: (optional) The event type that was created. :attr EventData data: (optional) Query event data object. """ def __init__(self, type=None, data=None): """ Initialize a CreateEventResponse object. :param str type: (optional) The event type that was created. :param EventData data: (optional) Query event data object. """ self.type = type self.data = data @classmethod def _from_dict(cls, _dict): """Initialize a CreateEventResponse object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'data' in _dict: args['data'] = EventData._from_dict(_dict.get('data')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'data') and self.data is not None: _dict['data'] = self.data._to_dict() return _dict def __str__(self): """Return a `str` version of this CreateEventResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CredentialDetails(object): """ Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. :attr str credential_type: (optional) The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The following combinations are possible: - `"source_type": "box"` - valid `credential_type`s: `oauth2` - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntml_v1` with **source_version** of `2016` - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic`. :attr str client_id: (optional) The **client_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. :attr str enterprise_id: (optional) The **enterprise_id** of the Box site that these credentials connect to. Only valid, and required, with a **source_type** of `box`. :attr str url: (optional) The **url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `username_password`, `noauth`, and `basic`. :attr str username: (optional) The **username** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`, `username_password`, `basic`, or `ntml_v1`. :attr str organization_url: (optional) The **organization_url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`. :attr str site_collection_path: (optional) The **site_collection.path** of the source that these credentials connect to. Only valid, and required, with a **source_type** of `sharepoint`. :attr str client_secret: (optional) The **client_secret** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :attr str public_key_id: (optional) The **public_key_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :attr str private_key: (optional) The **private_key** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :attr str passphrase: (optional) The **passphrase** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :attr str password: (optional) The **password** of the source that these credentials connect to. Only valid, and required, with **credential_type**s of `saml`, `username_password`, `basic`, or `ntml_v1`. **Note:** When used with a **source_type** of `salesforce`, the password consists of the Salesforce password and a valid Salesforce security token concatenated. This value is never returned and is only used when creating or modifying **credentials**. :attr str gateway_id: (optional) The ID of the **gateway** to be connected through (when connecting to intranet sites). Only valid with a **credential_type** of `noauth`, `basic`, or `ntml_v1`. Gateways are created using the `/v1/environments/{environment_id}/gateways` methods. :attr str source_version: (optional) The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. :attr str web_application_url: (optional) SharePoint OnPrem WebApplication URL. Only valid, and required, with a **source_version** of `2016`. :attr str domain: (optional) The domain used to log in to your OnPrem SharePoint account. Only valid, and required, with a **source_version** of `2016`. """ def __init__(self, credential_type=None, client_id=None, enterprise_id=None, url=None, username=None, organization_url=None, site_collection_path=None, client_secret=None, public_key_id=None, private_key=None, passphrase=None, password=None, gateway_id=None, source_version=None, web_application_url=None, domain=None): """ Initialize a CredentialDetails object. :param str credential_type: (optional) The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The following combinations are possible: - `"source_type": "box"` - valid `credential_type`s: `oauth2` - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntml_v1` with **source_version** of `2016` - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic`. :param str client_id: (optional) The **client_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. :param str enterprise_id: (optional) The **enterprise_id** of the Box site that these credentials connect to. Only valid, and required, with a **source_type** of `box`. :param str url: (optional) The **url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `username_password`, `noauth`, and `basic`. :param str username: (optional) The **username** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`, `username_password`, `basic`, or `ntml_v1`. :param str organization_url: (optional) The **organization_url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`. :param str site_collection_path: (optional) The **site_collection.path** of the source that these credentials connect to. Only valid, and required, with a **source_type** of `sharepoint`. :param str client_secret: (optional) The **client_secret** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :param str public_key_id: (optional) The **public_key_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :param str private_key: (optional) The **private_key** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :param str passphrase: (optional) The **passphrase** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. :param str password: (optional) The **password** of the source that these credentials connect to. Only valid, and required, with **credential_type**s of `saml`, `username_password`, `basic`, or `ntml_v1`. **Note:** When used with a **source_type** of `salesforce`, the password consists of the Salesforce password and a valid Salesforce security token concatenated. This value is never returned and is only used when creating or modifying **credentials**. :param str gateway_id: (optional) The ID of the **gateway** to be connected through (when connecting to intranet sites). Only valid with a **credential_type** of `noauth`, `basic`, or `ntml_v1`. Gateways are created using the `/v1/environments/{environment_id}/gateways` methods. :param str source_version: (optional) The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. :param str web_application_url: (optional) SharePoint OnPrem WebApplication URL. Only valid, and required, with a **source_version** of `2016`. :param str domain: (optional) The domain used to log in to your OnPrem SharePoint account. Only valid, and required, with a **source_version** of `2016`. """ self.credential_type = credential_type self.client_id = client_id self.enterprise_id = enterprise_id self.url = url self.username = username self.organization_url = organization_url self.site_collection_path = site_collection_path self.client_secret = client_secret self.public_key_id = public_key_id self.private_key = private_key self.passphrase = passphrase self.password = password self.gateway_id = gateway_id self.source_version = source_version self.web_application_url = web_application_url self.domain = domain @classmethod def _from_dict(cls, _dict): """Initialize a CredentialDetails object from a json dictionary.""" args = {} if 'credential_type' in _dict: args['credential_type'] = _dict.get('credential_type') if 'client_id' in _dict: args['client_id'] = _dict.get('client_id') if 'enterprise_id' in _dict: args['enterprise_id'] = _dict.get('enterprise_id') if 'url' in _dict: args['url'] = _dict.get('url') if 'username' in _dict: args['username'] = _dict.get('username') if 'organization_url' in _dict: args['organization_url'] = _dict.get('organization_url') if 'site_collection.path' in _dict: args['site_collection_path'] = _dict.get('site_collection.path') if 'client_secret' in _dict: args['client_secret'] = _dict.get('client_secret') if 'public_key_id' in _dict: args['public_key_id'] = _dict.get('public_key_id') if 'private_key' in _dict: args['private_key'] = _dict.get('private_key') if 'passphrase' in _dict: args['passphrase'] = _dict.get('passphrase') if 'password' in _dict: args['password'] = _dict.get('password') if 'gateway_id' in _dict: args['gateway_id'] = _dict.get('gateway_id') if 'source_version' in _dict: args['source_version'] = _dict.get('source_version') if 'web_application_url' in _dict: args['web_application_url'] = _dict.get('web_application_url') if 'domain' in _dict: args['domain'] = _dict.get('domain') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_type') and self.credential_type is not None: _dict['credential_type'] = self.credential_type if hasattr(self, 'client_id') and self.client_id is not None: _dict['client_id'] = self.client_id if hasattr(self, 'enterprise_id') and self.enterprise_id is not None: _dict['enterprise_id'] = self.enterprise_id if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'username') and self.username is not None: _dict['username'] = self.username if hasattr(self, 'organization_url') and self.organization_url is not None: _dict['organization_url'] = self.organization_url if hasattr(self, 'site_collection_path' ) and self.site_collection_path is not None: _dict['site_collection.path'] = self.site_collection_path if hasattr(self, 'client_secret') and self.client_secret is not None: _dict['client_secret'] = self.client_secret if hasattr(self, 'public_key_id') and self.public_key_id is not None: _dict['public_key_id'] = self.public_key_id if hasattr(self, 'private_key') and self.private_key is not None: _dict['private_key'] = self.private_key if hasattr(self, 'passphrase') and self.passphrase is not None: _dict['passphrase'] = self.passphrase if hasattr(self, 'password') and self.password is not None: _dict['password'] = self.password if hasattr(self, 'gateway_id') and self.gateway_id is not None: _dict['gateway_id'] = self.gateway_id if hasattr(self, 'source_version') and self.source_version is not None: _dict['source_version'] = self.source_version if hasattr( self, 'web_application_url') and self.web_application_url is not None: _dict['web_application_url'] = self.web_application_url if hasattr(self, 'domain') and self.domain is not None: _dict['domain'] = self.domain return _dict def __str__(self): """Return a `str` version of this CredentialDetails object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Credentials(object): """ Object containing credential information. :attr str credential_id: (optional) Unique identifier for this set of credentials. :attr str source_type: (optional) The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of Enterprise Box. - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. :attr CredentialDetails credential_details: (optional) Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. """ def __init__(self, credential_id=None, source_type=None, credential_details=None): """ Initialize a Credentials object. :param str credential_id: (optional) Unique identifier for this set of credentials. :param str source_type: (optional) The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of Enterprise Box. - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. :param CredentialDetails credential_details: (optional) Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. """ self.credential_id = credential_id self.source_type = source_type self.credential_details = credential_details @classmethod def _from_dict(cls, _dict): """Initialize a Credentials object from a json dictionary.""" args = {} if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'source_type' in _dict: args['source_type'] = _dict.get('source_type') if 'credential_details' in _dict: args['credential_details'] = CredentialDetails._from_dict( _dict.get('credential_details')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'source_type') and self.source_type is not None: _dict['source_type'] = self.source_type if hasattr( self, 'credential_details') and self.credential_details is not None: _dict['credential_details'] = self.credential_details._to_dict() return _dict def __str__(self): """Return a `str` version of this Credentials object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CredentialsList(object): """ CredentialsList. :attr list[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ def __init__(self, credentials=None): """ Initialize a CredentialsList object. :param list[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ self.credentials = credentials @classmethod def _from_dict(cls, _dict): """Initialize a CredentialsList object from a json dictionary.""" args = {} if 'credentials' in _dict: args['credentials'] = [ Credentials._from_dict(x) for x in (_dict.get('credentials')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credentials') and self.credentials is not None: _dict['credentials'] = [x._to_dict() for x in self.credentials] return _dict def __str__(self): """Return a `str` version of this CredentialsList object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DeleteCollectionResponse(object): """ DeleteCollectionResponse. :attr str collection_id: The unique identifier of the collection that is being deleted. :attr str status: The status of the collection. The status of a successful deletion operation is `deleted`. """ def __init__(self, collection_id, status): """ Initialize a DeleteCollectionResponse object. :param str collection_id: The unique identifier of the collection that is being deleted. :param str status: The status of the collection. The status of a successful deletion operation is `deleted`. """ self.collection_id = collection_id self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a DeleteCollectionResponse object from a json dictionary.""" args = {} if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') else: raise ValueError( 'Required property \'collection_id\' not present in DeleteCollectionResponse JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in DeleteCollectionResponse JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this DeleteCollectionResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DeleteConfigurationResponse(object): """ DeleteConfigurationResponse. :attr str configuration_id: The unique identifier for the configuration. :attr str status: Status of the configuration. A deleted configuration has the status deleted. :attr list[Notice] notices: (optional) An array of notice messages, if any. """ def __init__(self, configuration_id, status, notices=None): """ Initialize a DeleteConfigurationResponse object. :param str configuration_id: The unique identifier for the configuration. :param str status: Status of the configuration. A deleted configuration has the status deleted. :param list[Notice] notices: (optional) An array of notice messages, if any. """ self.configuration_id = configuration_id self.status = status self.notices = notices @classmethod def _from_dict(cls, _dict): """Initialize a DeleteConfigurationResponse object from a json dictionary.""" args = {} if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') else: raise ValueError( 'Required property \'configuration_id\' not present in DeleteConfigurationResponse JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in DeleteConfigurationResponse JSON' ) if 'notices' in _dict: args['notices'] = [ Notice._from_dict(x) for x in (_dict.get('notices')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configuration_id') and self.configuration_id is not None: _dict['configuration_id'] = self.configuration_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: _dict['notices'] = [x._to_dict() for x in self.notices] return _dict def __str__(self): """Return a `str` version of this DeleteConfigurationResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DeleteCredentials(object): """ Object returned after credentials are deleted. :attr str credential_id: (optional) The unique identifier of the credentials that have been deleted. :attr str status: (optional) The status of the deletion request. """ def __init__(self, credential_id=None, status=None): """ Initialize a DeleteCredentials object. :param str credential_id: (optional) The unique identifier of the credentials that have been deleted. :param str status: (optional) The status of the deletion request. """ self.credential_id = credential_id self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a DeleteCredentials object from a json dictionary.""" args = {} if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'status' in _dict: args['status'] = _dict.get('status') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this DeleteCredentials object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DeleteDocumentResponse(object): """ DeleteDocumentResponse. :attr str document_id: (optional) The unique identifier of the document. :attr str status: (optional) Status of the document. A deleted document has the status deleted. """ def __init__(self, document_id=None, status=None): """ Initialize a DeleteDocumentResponse object. :param str document_id: (optional) The unique identifier of the document. :param str status: (optional) Status of the document. A deleted document has the status deleted. """ self.document_id = document_id self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: args['status'] = _dict.get('status') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this DeleteDocumentResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DeleteEnvironmentResponse(object): """ DeleteEnvironmentResponse. :attr str environment_id: The unique identifier for the environment. :attr str status: Status of the environment. """ def __init__(self, environment_id, status): """ Initialize a DeleteEnvironmentResponse object. :param str environment_id: The unique identifier for the environment. :param str status: Status of the environment. """ self.environment_id = environment_id self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') else: raise ValueError( 'Required property \'environment_id\' not present in DeleteEnvironmentResponse JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in DeleteEnvironmentResponse JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environment_id') and self.environment_id is not None: _dict['environment_id'] = self.environment_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this DeleteEnvironmentResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DiskUsage(object): """ Summary of the disk usage statistics for the environment. :attr int used_bytes: (optional) Number of bytes within the environment's disk capacity that are currently used to store data. :attr int maximum_allowed_bytes: (optional) Total number of bytes available in the environment's disk capacity. :attr int total_bytes: (optional) **Deprecated**: Total number of bytes available in the environment's disk capacity. :attr str used: (optional) **Deprecated**: Amount of disk capacity used, in KB or GB format. :attr str total: (optional) **Deprecated**: Total amount of the environment's disk capacity, in KB or GB format. :attr float percent_used: (optional) **Deprecated**: Percentage of the environment's disk capacity that is being used. """ def __init__(self, used_bytes=None, maximum_allowed_bytes=None, total_bytes=None, used=None, total=None, percent_used=None): """ Initialize a DiskUsage object. :param int used_bytes: (optional) Number of bytes within the environment's disk capacity that are currently used to store data. :param int maximum_allowed_bytes: (optional) Total number of bytes available in the environment's disk capacity. :param int total_bytes: (optional) **Deprecated**: Total number of bytes available in the environment's disk capacity. :param str used: (optional) **Deprecated**: Amount of disk capacity used, in KB or GB format. :param str total: (optional) **Deprecated**: Total amount of the environment's disk capacity, in KB or GB format. :param float percent_used: (optional) **Deprecated**: Percentage of the environment's disk capacity that is being used. """ self.used_bytes = used_bytes self.maximum_allowed_bytes = maximum_allowed_bytes self.total_bytes = total_bytes self.used = used self.total = total self.percent_used = percent_used @classmethod def _from_dict(cls, _dict): """Initialize a DiskUsage object from a json dictionary.""" args = {} if 'used_bytes' in _dict: args['used_bytes'] = _dict.get('used_bytes') if 'maximum_allowed_bytes' in _dict: args['maximum_allowed_bytes'] = _dict.get('maximum_allowed_bytes') if 'total_bytes' in _dict: args['total_bytes'] = _dict.get('total_bytes') if 'used' in _dict: args['used'] = _dict.get('used') if 'total' in _dict: args['total'] = _dict.get('total') if 'percent_used' in _dict: args['percent_used'] = _dict.get('percent_used') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'used_bytes') and self.used_bytes is not None: _dict['used_bytes'] = self.used_bytes if hasattr(self, 'maximum_allowed_bytes' ) and self.maximum_allowed_bytes is not None: _dict['maximum_allowed_bytes'] = self.maximum_allowed_bytes if hasattr(self, 'total_bytes') and self.total_bytes is not None: _dict['total_bytes'] = self.total_bytes if hasattr(self, 'used') and self.used is not None: _dict['used'] = self.used if hasattr(self, 'total') and self.total is not None: _dict['total'] = self.total if hasattr(self, 'percent_used') and self.percent_used is not None: _dict['percent_used'] = self.percent_used return _dict def __str__(self): """Return a `str` version of this DiskUsage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentAccepted(object): """ DocumentAccepted. :attr str document_id: (optional) The unique identifier of the ingested document. :attr str status: (optional) Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. :attr list[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ def __init__(self, document_id=None, status=None, notices=None): """ Initialize a DocumentAccepted object. :param str document_id: (optional) The unique identifier of the ingested document. :param str status: (optional) Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. :param list[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ self.document_id = document_id self.status = status self.notices = notices @classmethod def _from_dict(cls, _dict): """Initialize a DocumentAccepted object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: args['status'] = _dict.get('status') if 'notices' in _dict: args['notices'] = [ Notice._from_dict(x) for x in (_dict.get('notices')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: _dict['notices'] = [x._to_dict() for x in self.notices] return _dict def __str__(self): """Return a `str` version of this DocumentAccepted object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentCounts(object): """ DocumentCounts. :attr int available: (optional) The total number of available documents in the collection. :attr int processing: (optional) The number of documents in the collection that are currently being processed. :attr int failed: (optional) The number of documents in the collection that failed to be ingested. :attr int pending: (optional) The number of documents that have been uploaded to the collection, but have not yet started processing. """ def __init__(self, available=None, processing=None, failed=None, pending=None): """ Initialize a DocumentCounts object. :param int available: (optional) The total number of available documents in the collection. :param int processing: (optional) The number of documents in the collection that are currently being processed. :param int failed: (optional) The number of documents in the collection that failed to be ingested. :param int pending: (optional) The number of documents that have been uploaded to the collection, but have not yet started processing. """ self.available = available self.processing = processing self.failed = failed self.pending = pending @classmethod def _from_dict(cls, _dict): """Initialize a DocumentCounts object from a json dictionary.""" args = {} if 'available' in _dict: args['available'] = _dict.get('available') if 'processing' in _dict: args['processing'] = _dict.get('processing') if 'failed' in _dict: args['failed'] = _dict.get('failed') if 'pending' in _dict: args['pending'] = _dict.get('pending') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'available') and self.available is not None: _dict['available'] = self.available if hasattr(self, 'processing') and self.processing is not None: _dict['processing'] = self.processing if hasattr(self, 'failed') and self.failed is not None: _dict['failed'] = self.failed if hasattr(self, 'pending') and self.pending is not None: _dict['pending'] = self.pending return _dict def __str__(self): """Return a `str` version of this DocumentCounts object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentSnapshot(object): """ DocumentSnapshot. :attr str step: (optional) :attr object snapshot: (optional) """ def __init__(self, step=None, snapshot=None): """ Initialize a DocumentSnapshot object. :param str step: (optional) :param object snapshot: (optional) """ self.step = step self.snapshot = snapshot @classmethod def _from_dict(cls, _dict): """Initialize a DocumentSnapshot object from a json dictionary.""" args = {} if 'step' in _dict: args['step'] = _dict.get('step') if 'snapshot' in _dict: args['snapshot'] = _dict.get('snapshot') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'step') and self.step is not None: _dict['step'] = self.step if hasattr(self, 'snapshot') and self.snapshot is not None: _dict['snapshot'] = self.snapshot return _dict def __str__(self): """Return a `str` version of this DocumentSnapshot object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentStatus(object): """ Status information about a submitted document. :attr str document_id: The unique identifier of the document. :attr str configuration_id: (optional) The unique identifier for the configuration. :attr datetime created: (optional) The creation date of the document in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr datetime updated: (optional) Date of the most recent document update, in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str status: Status of the document in the ingestion process. :attr str status_description: Description of the document status. :attr str filename: (optional) Name of the original source file (if available). :attr str file_type: (optional) The type of the original source file. :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). :attr list[Notice] notices: Array of notices produced by the document-ingestion process. """ def __init__(self, document_id, status, status_description, notices, configuration_id=None, created=None, updated=None, filename=None, file_type=None, sha1=None): """ Initialize a DocumentStatus object. :param str document_id: The unique identifier of the document. :param str status: Status of the document in the ingestion process. :param str status_description: Description of the document status. :param list[Notice] notices: Array of notices produced by the document-ingestion process. :param str configuration_id: (optional) The unique identifier for the configuration. :param datetime created: (optional) The creation date of the document in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param datetime updated: (optional) Date of the most recent document update, in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str filename: (optional) Name of the original source file (if available). :param str file_type: (optional) The type of the original source file. :param str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). """ self.document_id = document_id self.configuration_id = configuration_id self.created = created self.updated = updated self.status = status self.status_description = status_description self.filename = filename self.file_type = file_type self.sha1 = sha1 self.notices = notices @classmethod def _from_dict(cls, _dict): """Initialize a DocumentStatus object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: raise ValueError( 'Required property \'document_id\' not present in DocumentStatus JSON' ) if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in DocumentStatus JSON' ) if 'status_description' in _dict: args['status_description'] = _dict.get('status_description') else: raise ValueError( 'Required property \'status_description\' not present in DocumentStatus JSON' ) if 'filename' in _dict: args['filename'] = _dict.get('filename') if 'file_type' in _dict: args['file_type'] = _dict.get('file_type') if 'sha1' in _dict: args['sha1'] = _dict.get('sha1') if 'notices' in _dict: args['notices'] = [ Notice._from_dict(x) for x in (_dict.get('notices')) ] else: raise ValueError( 'Required property \'notices\' not present in DocumentStatus JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'configuration_id') and self.configuration_id is not None: _dict['configuration_id'] = self.configuration_id if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr( self, 'status_description') and self.status_description is not None: _dict['status_description'] = self.status_description if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'file_type') and self.file_type is not None: _dict['file_type'] = self.file_type if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 if hasattr(self, 'notices') and self.notices is not None: _dict['notices'] = [x._to_dict() for x in self.notices] return _dict def __str__(self): """Return a `str` version of this DocumentStatus object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Enrichment(object): """ Enrichment. :attr str description: (optional) Describes what the enrichment step does. :attr str destination_field: Field where enrichments will be stored. This field must already exist or be at most 1 level deeper than an existing field. For example, if `text` is a top-level field with no sub-fields, `text.foo` is a valid destination but `text.foo.bar` is not. :attr str source_field: Field to be enriched. :attr bool overwrite: (optional) Indicates that the enrichments will overwrite the destination_field field if it already exists. :attr str enrichment_name: Name of the enrichment service to call. Current options are `natural_language_understanding` and `elements`. When using `natual_language_understanding`, the **options** object must contain Natural Language Understanding options. When using `elements` the **options** object must contain Element Classification options. Additionally, when using the `elements` enrichment the configuration specified and files ingested must meet all the criteria specified in [the documentation](https://console.bluemix.net/docs/services/discovery/element-classification.html) Previous API versions also supported `alchemy_language`. :attr bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. :attr EnrichmentOptions options: (optional) Options which are specific to a particular enrichment. """ def __init__(self, destination_field, source_field, enrichment_name, description=None, overwrite=None, ignore_downstream_errors=None, options=None): """ Initialize a Enrichment object. :param str destination_field: Field where enrichments will be stored. This field must already exist or be at most 1 level deeper than an existing field. For example, if `text` is a top-level field with no sub-fields, `text.foo` is a valid destination but `text.foo.bar` is not. :param str source_field: Field to be enriched. :param str enrichment_name: Name of the enrichment service to call. Current options are `natural_language_understanding` and `elements`. When using `natual_language_understanding`, the **options** object must contain Natural Language Understanding options. When using `elements` the **options** object must contain Element Classification options. Additionally, when using the `elements` enrichment the configuration specified and files ingested must meet all the criteria specified in [the documentation](https://console.bluemix.net/docs/services/discovery/element-classification.html) Previous API versions also supported `alchemy_language`. :param str description: (optional) Describes what the enrichment step does. :param bool overwrite: (optional) Indicates that the enrichments will overwrite the destination_field field if it already exists. :param bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. :param EnrichmentOptions options: (optional) Options which are specific to a particular enrichment. """ self.description = description self.destination_field = destination_field self.source_field = source_field self.overwrite = overwrite self.enrichment_name = enrichment_name self.ignore_downstream_errors = ignore_downstream_errors self.options = options @classmethod def _from_dict(cls, _dict): """Initialize a Enrichment object from a json dictionary.""" args = {} if 'description' in _dict: args['description'] = _dict.get('description') if 'destination_field' in _dict: args['destination_field'] = _dict.get('destination_field') else: raise ValueError( 'Required property \'destination_field\' not present in Enrichment JSON' ) if 'source_field' in _dict: args['source_field'] = _dict.get('source_field') else: raise ValueError( 'Required property \'source_field\' not present in Enrichment JSON' ) if 'overwrite' in _dict: args['overwrite'] = _dict.get('overwrite') if 'enrichment' in _dict or 'enrichment_name' in _dict: args['enrichment_name'] = _dict.get('enrichment') or _dict.get( 'enrichment_name') else: raise ValueError( 'Required property \'enrichment\' not present in Enrichment JSON' ) if 'ignore_downstream_errors' in _dict: args['ignore_downstream_errors'] = _dict.get( 'ignore_downstream_errors') if 'options' in _dict: args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'destination_field') and self.destination_field is not None: _dict['destination_field'] = self.destination_field if hasattr(self, 'source_field') and self.source_field is not None: _dict['source_field'] = self.source_field if hasattr(self, 'overwrite') and self.overwrite is not None: _dict['overwrite'] = self.overwrite if hasattr(self, 'enrichment_name') and self.enrichment_name is not None: _dict['enrichment'] = self.enrichment_name if hasattr(self, 'ignore_downstream_errors' ) and self.ignore_downstream_errors is not None: _dict['ignore_downstream_errors'] = self.ignore_downstream_errors if hasattr(self, 'options') and self.options is not None: _dict['options'] = self.options._to_dict() return _dict def __str__(self): """Return a `str` version of this Enrichment object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EnrichmentOptions(object): """ Options which are specific to a particular enrichment. :attr NluEnrichmentFeatures features: (optional) An object representing the enrichment features that will be applied to the specified field. :attr str language: (optional) ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. :attr str model: (optional) *For use with `elements` enrichments only.* The element extraction model to use. Models available are: `contract`. """ def __init__(self, features=None, language=None, model=None): """ Initialize a EnrichmentOptions object. :param NluEnrichmentFeatures features: (optional) An object representing the enrichment features that will be applied to the specified field. :param str language: (optional) ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. :param str model: (optional) *For use with `elements` enrichments only.* The element extraction model to use. Models available are: `contract`. """ self.features = features self.language = language self.model = model @classmethod def _from_dict(cls, _dict): """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} if 'features' in _dict: args['features'] = NluEnrichmentFeatures._from_dict( _dict.get('features')) if 'language' in _dict: args['language'] = _dict.get('language') if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'features') and self.features is not None: _dict['features'] = self.features._to_dict() if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'model') and self.model is not None: _dict['model'] = self.model return _dict def __str__(self): """Return a `str` version of this EnrichmentOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Environment(object): """ Details about an environment. :attr str environment_id: (optional) Unique identifier for the environment. :attr str name: (optional) Name that identifies the environment. :attr str description: (optional) Description of the environment. :attr datetime created: (optional) Creation date of the environment, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. :attr datetime updated: (optional) Date of most recent environment update, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. :attr str status: (optional) Current status of the environment. `resizing` is displayed when a request to increase the environment size has been made, but is still in the process of being completed. :attr bool read_only: (optional) If `true`, the environment contains read-only collections that are maintained by IBM. :attr str size: (optional) Current size of the environment. :attr str requested_size: (optional) The new size requested for this environment. Only returned when the environment *status* is `resizing`. *Note:* Querying and indexing can still be performed during an environment upsize. :attr IndexCapacity index_capacity: (optional) Details about the resource usage and capacity of the environment. :attr SearchStatus search_status: (optional) Information about the Continuous Relevancy Training for this environment. """ def __init__(self, environment_id=None, name=None, description=None, created=None, updated=None, status=None, read_only=None, size=None, requested_size=None, index_capacity=None, search_status=None): """ Initialize a Environment object. :param str environment_id: (optional) Unique identifier for the environment. :param str name: (optional) Name that identifies the environment. :param str description: (optional) Description of the environment. :param datetime created: (optional) Creation date of the environment, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. :param datetime updated: (optional) Date of most recent environment update, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. :param str status: (optional) Current status of the environment. `resizing` is displayed when a request to increase the environment size has been made, but is still in the process of being completed. :param bool read_only: (optional) If `true`, the environment contains read-only collections that are maintained by IBM. :param str size: (optional) Current size of the environment. :param str requested_size: (optional) The new size requested for this environment. Only returned when the environment *status* is `resizing`. *Note:* Querying and indexing can still be performed during an environment upsize. :param IndexCapacity index_capacity: (optional) Details about the resource usage and capacity of the environment. :param SearchStatus search_status: (optional) Information about the Continuous Relevancy Training for this environment. """ self.environment_id = environment_id self.name = name self.description = description self.created = created self.updated = updated self.status = status self.read_only = read_only self.size = size self.requested_size = requested_size self.index_capacity = index_capacity self.search_status = search_status @classmethod def _from_dict(cls, _dict): """Initialize a Environment object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'name' in _dict: args['name'] = _dict.get('name') if 'description' in _dict: args['description'] = _dict.get('description') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'status' in _dict: args['status'] = _dict.get('status') if 'read_only' in _dict: args['read_only'] = _dict.get('read_only') if 'size' in _dict: args['size'] = _dict.get('size') if 'requested_size' in _dict: args['requested_size'] = _dict.get('requested_size') if 'index_capacity' in _dict: args['index_capacity'] = IndexCapacity._from_dict( _dict.get('index_capacity')) if 'search_status' in _dict: args['search_status'] = SearchStatus._from_dict( _dict.get('search_status')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environment_id') and self.environment_id is not None: _dict['environment_id'] = self.environment_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'read_only') and self.read_only is not None: _dict['read_only'] = self.read_only if hasattr(self, 'size') and self.size is not None: _dict['size'] = self.size if hasattr(self, 'requested_size') and self.requested_size is not None: _dict['requested_size'] = self.requested_size if hasattr(self, 'index_capacity') and self.index_capacity is not None: _dict['index_capacity'] = self.index_capacity._to_dict() if hasattr(self, 'search_status') and self.search_status is not None: _dict['search_status'] = self.search_status._to_dict() return _dict def __str__(self): """Return a `str` version of this Environment object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EnvironmentDocuments(object): """ Summary of the document usage statistics for the environment. :attr int indexed: (optional) Number of documents indexed for the environment. :attr int maximum_allowed: (optional) Total number of documents allowed in the environment's capacity. """ def __init__(self, indexed=None, maximum_allowed=None): """ Initialize a EnvironmentDocuments object. :param int indexed: (optional) Number of documents indexed for the environment. :param int maximum_allowed: (optional) Total number of documents allowed in the environment's capacity. """ self.indexed = indexed self.maximum_allowed = maximum_allowed @classmethod def _from_dict(cls, _dict): """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} if 'indexed' in _dict: args['indexed'] = _dict.get('indexed') if 'maximum_allowed' in _dict: args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'indexed') and self.indexed is not None: _dict['indexed'] = self.indexed if hasattr(self, 'maximum_allowed') and self.maximum_allowed is not None: _dict['maximum_allowed'] = self.maximum_allowed return _dict def __str__(self): """Return a `str` version of this EnvironmentDocuments object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EventData(object): """ Query event data object. :attr str environment_id: The **environment_id** associated with the query that the event is associated with. :attr str session_token: The session token that was returned as part of the query results that this event is associated with. :attr datetime client_timestamp: (optional) The optional timestamp for the event that was created. If not provided, the time that the event was created in the log was used. :attr int display_rank: (optional) The rank of the result item which the event is associated with. :attr str collection_id: The **collection_id** of the document that this event is associated with. :attr str document_id: The **document_id** of the document that this event is associated with. :attr str query_id: (optional) The query identifier stored in the log. The query and any events associated with that query are stored with the same **query_id**. """ def __init__(self, environment_id, session_token, collection_id, document_id, client_timestamp=None, display_rank=None, query_id=None): """ Initialize a EventData object. :param str environment_id: The **environment_id** associated with the query that the event is associated with. :param str session_token: The session token that was returned as part of the query results that this event is associated with. :param str collection_id: The **collection_id** of the document that this event is associated with. :param str document_id: The **document_id** of the document that this event is associated with. :param datetime client_timestamp: (optional) The optional timestamp for the event that was created. If not provided, the time that the event was created in the log was used. :param int display_rank: (optional) The rank of the result item which the event is associated with. :param str query_id: (optional) The query identifier stored in the log. The query and any events associated with that query are stored with the same **query_id**. """ self.environment_id = environment_id self.session_token = session_token self.client_timestamp = client_timestamp self.display_rank = display_rank self.collection_id = collection_id self.document_id = document_id self.query_id = query_id @classmethod def _from_dict(cls, _dict): """Initialize a EventData object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') else: raise ValueError( 'Required property \'environment_id\' not present in EventData JSON' ) if 'session_token' in _dict: args['session_token'] = _dict.get('session_token') else: raise ValueError( 'Required property \'session_token\' not present in EventData JSON' ) if 'client_timestamp' in _dict: args['client_timestamp'] = string_to_datetime( _dict.get('client_timestamp')) if 'display_rank' in _dict: args['display_rank'] = _dict.get('display_rank') if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') else: raise ValueError( 'Required property \'collection_id\' not present in EventData JSON' ) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: raise ValueError( 'Required property \'document_id\' not present in EventData JSON' ) if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environment_id') and self.environment_id is not None: _dict['environment_id'] = self.environment_id if hasattr(self, 'session_token') and self.session_token is not None: _dict['session_token'] = self.session_token if hasattr(self, 'client_timestamp') and self.client_timestamp is not None: _dict['client_timestamp'] = datetime_to_string( self.client_timestamp) if hasattr(self, 'display_rank') and self.display_rank is not None: _dict['display_rank'] = self.display_rank if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'query_id') and self.query_id is not None: _dict['query_id'] = self.query_id return _dict def __str__(self): """Return a `str` version of this EventData object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Expansion(object): """ An expansion definition. Each object respresents one set of expandable strings. For example, you could have expansions for the word `hot` in one object, and expansions for the word `cold` in another. :attr list[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. :attr list[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, it also functions as the input term list. """ def __init__(self, expanded_terms, input_terms=None): """ Initialize a Expansion object. :param list[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, it also functions as the input term list. :param list[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. """ self.input_terms = input_terms self.expanded_terms = expanded_terms @classmethod def _from_dict(cls, _dict): """Initialize a Expansion object from a json dictionary.""" args = {} if 'input_terms' in _dict: args['input_terms'] = _dict.get('input_terms') if 'expanded_terms' in _dict: args['expanded_terms'] = _dict.get('expanded_terms') else: raise ValueError( 'Required property \'expanded_terms\' not present in Expansion JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input_terms') and self.input_terms is not None: _dict['input_terms'] = self.input_terms if hasattr(self, 'expanded_terms') and self.expanded_terms is not None: _dict['expanded_terms'] = self.expanded_terms return _dict def __str__(self): """Return a `str` version of this Expansion object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Expansions(object): """ The query expansion definitions for the specified collection. :attr list[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all terms are expanded to all other terms in the object. Unidirectional means that a set list of terms can be expanded into a second list of terms. To create a bi-directional expansion specify an **expanded_terms** array. When found in a query, all items in the **expanded_terms** array are then expanded to the other items in the same array. To create a uni-directional expansion, specify both an array of **input_terms** and an array of **expanded_terms**. When items in the **input_terms** array are present in a query, they are expanded using the items listed in the **expanded_terms** array. """ def __init__(self, expansions): """ Initialize a Expansions object. :param list[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all terms are expanded to all other terms in the object. Unidirectional means that a set list of terms can be expanded into a second list of terms. To create a bi-directional expansion specify an **expanded_terms** array. When found in a query, all items in the **expanded_terms** array are then expanded to the other items in the same array. To create a uni-directional expansion, specify both an array of **input_terms** and an array of **expanded_terms**. When items in the **input_terms** array are present in a query, they are expanded using the items listed in the **expanded_terms** array. """ self.expansions = expansions @classmethod def _from_dict(cls, _dict): """Initialize a Expansions object from a json dictionary.""" args = {} if 'expansions' in _dict: args['expansions'] = [ Expansion._from_dict(x) for x in (_dict.get('expansions')) ] else: raise ValueError( 'Required property \'expansions\' not present in Expansions JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'expansions') and self.expansions is not None: _dict['expansions'] = [x._to_dict() for x in self.expansions] return _dict def __str__(self): """Return a `str` version of this Expansions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Field(object): """ Field. :attr str field_name: (optional) The name of the field. :attr str field_type: (optional) The type of the field. """ def __init__(self, field_name=None, field_type=None): """ Initialize a Field object. :param str field_name: (optional) The name of the field. :param str field_type: (optional) The type of the field. """ self.field_name = field_name self.field_type = field_type @classmethod def _from_dict(cls, _dict): """Initialize a Field object from a json dictionary.""" args = {} if 'field' in _dict or 'field_name' in _dict: args['field_name'] = _dict.get('field') or _dict.get('field_name') if 'type' in _dict or 'field_type' in _dict: args['field_type'] = _dict.get('type') or _dict.get('field_type') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'field_name') and self.field_name is not None: _dict['field'] = self.field_name if hasattr(self, 'field_type') and self.field_type is not None: _dict['type'] = self.field_type return _dict def __str__(self): """Return a `str` version of this Field object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FontSetting(object): """ FontSetting. :attr int level: (optional) :attr int min_size: (optional) :attr int max_size: (optional) :attr bool bold: (optional) :attr bool italic: (optional) :attr str name: (optional) """ def __init__(self, level=None, min_size=None, max_size=None, bold=None, italic=None, name=None): """ Initialize a FontSetting object. :param int level: (optional) :param int min_size: (optional) :param int max_size: (optional) :param bool bold: (optional) :param bool italic: (optional) :param str name: (optional) """ self.level = level self.min_size = min_size self.max_size = max_size self.bold = bold self.italic = italic self.name = name @classmethod def _from_dict(cls, _dict): """Initialize a FontSetting object from a json dictionary.""" args = {} if 'level' in _dict: args['level'] = _dict.get('level') if 'min_size' in _dict: args['min_size'] = _dict.get('min_size') if 'max_size' in _dict: args['max_size'] = _dict.get('max_size') if 'bold' in _dict: args['bold'] = _dict.get('bold') if 'italic' in _dict: args['italic'] = _dict.get('italic') if 'name' in _dict: args['name'] = _dict.get('name') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'level') and self.level is not None: _dict['level'] = self.level if hasattr(self, 'min_size') and self.min_size is not None: _dict['min_size'] = self.min_size if hasattr(self, 'max_size') and self.max_size is not None: _dict['max_size'] = self.max_size if hasattr(self, 'bold') and self.bold is not None: _dict['bold'] = self.bold if hasattr(self, 'italic') and self.italic is not None: _dict['italic'] = self.italic if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name return _dict def __str__(self): """Return a `str` version of this FontSetting object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Gateway(object): """ Object describing a specific gateway. :attr str gateway_id: (optional) The gateway ID of the gateway. :attr str name: (optional) The user defined name of the gateway. :attr str status: (optional) The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway. `idle` means this gateway is not currently in use. :attr str token: (optional) The generated **token** for this gateway. The value of this field is used when configuring the remotly installed gateway. :attr str token_id: (optional) The generated **token_id** for this gateway. The value of this field is used when configuring the remotly installed gateway. """ def __init__(self, gateway_id=None, name=None, status=None, token=None, token_id=None): """ Initialize a Gateway object. :param str gateway_id: (optional) The gateway ID of the gateway. :param str name: (optional) The user defined name of the gateway. :param str status: (optional) The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway. `idle` means this gateway is not currently in use. :param str token: (optional) The generated **token** for this gateway. The value of this field is used when configuring the remotly installed gateway. :param str token_id: (optional) The generated **token_id** for this gateway. The value of this field is used when configuring the remotly installed gateway. """ self.gateway_id = gateway_id self.name = name self.status = status self.token = token self.token_id = token_id @classmethod def _from_dict(cls, _dict): """Initialize a Gateway object from a json dictionary.""" args = {} if 'gateway_id' in _dict: args['gateway_id'] = _dict.get('gateway_id') if 'name' in _dict: args['name'] = _dict.get('name') if 'status' in _dict: args['status'] = _dict.get('status') if 'token' in _dict: args['token'] = _dict.get('token') if 'token_id' in _dict: args['token_id'] = _dict.get('token_id') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'gateway_id') and self.gateway_id is not None: _dict['gateway_id'] = self.gateway_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'token') and self.token is not None: _dict['token'] = self.token if hasattr(self, 'token_id') and self.token_id is not None: _dict['token_id'] = self.token_id return _dict def __str__(self): """Return a `str` version of this Gateway object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class GatewayDelete(object): """ Gatway deletion confirmation. :attr str gateway_id: (optional) The gateway ID of the deleted gateway. :attr str status: (optional) The status of the request. """ def __init__(self, gateway_id=None, status=None): """ Initialize a GatewayDelete object. :param str gateway_id: (optional) The gateway ID of the deleted gateway. :param str status: (optional) The status of the request. """ self.gateway_id = gateway_id self.status = status @classmethod def _from_dict(cls, _dict): """Initialize a GatewayDelete object from a json dictionary.""" args = {} if 'gateway_id' in _dict: args['gateway_id'] = _dict.get('gateway_id') if 'status' in _dict: args['status'] = _dict.get('status') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'gateway_id') and self.gateway_id is not None: _dict['gateway_id'] = self.gateway_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict def __str__(self): """Return a `str` version of this GatewayDelete object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class GatewayList(object): """ Object containing gateways array. :attr list[Gateway] gateways: (optional) Array of configured gateway connections. """ def __init__(self, gateways=None): """ Initialize a GatewayList object. :param list[Gateway] gateways: (optional) Array of configured gateway connections. """ self.gateways = gateways @classmethod def _from_dict(cls, _dict): """Initialize a GatewayList object from a json dictionary.""" args = {} if 'gateways' in _dict: args['gateways'] = [ Gateway._from_dict(x) for x in (_dict.get('gateways')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'gateways') and self.gateways is not None: _dict['gateways'] = [x._to_dict() for x in self.gateways] return _dict def __str__(self): """Return a `str` version of this GatewayList object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class HtmlSettings(object): """ A list of HTML conversion settings. :attr list[str] exclude_tags_completely: (optional) :attr list[str] exclude_tags_keep_content: (optional) :attr XPathPatterns keep_content: (optional) :attr XPathPatterns exclude_content: (optional) :attr list[str] keep_tag_attributes: (optional) :attr list[str] exclude_tag_attributes: (optional) """ def __init__(self, exclude_tags_completely=None, exclude_tags_keep_content=None, keep_content=None, exclude_content=None, keep_tag_attributes=None, exclude_tag_attributes=None): """ Initialize a HtmlSettings object. :param list[str] exclude_tags_completely: (optional) :param list[str] exclude_tags_keep_content: (optional) :param XPathPatterns keep_content: (optional) :param XPathPatterns exclude_content: (optional) :param list[str] keep_tag_attributes: (optional) :param list[str] exclude_tag_attributes: (optional) """ self.exclude_tags_completely = exclude_tags_completely self.exclude_tags_keep_content = exclude_tags_keep_content self.keep_content = keep_content self.exclude_content = exclude_content self.keep_tag_attributes = keep_tag_attributes self.exclude_tag_attributes = exclude_tag_attributes @classmethod def _from_dict(cls, _dict): """Initialize a HtmlSettings object from a json dictionary.""" args = {} if 'exclude_tags_completely' in _dict: args['exclude_tags_completely'] = _dict.get( 'exclude_tags_completely') if 'exclude_tags_keep_content' in _dict: args['exclude_tags_keep_content'] = _dict.get( 'exclude_tags_keep_content') if 'keep_content' in _dict: args['keep_content'] = XPathPatterns._from_dict( _dict.get('keep_content')) if 'exclude_content' in _dict: args['exclude_content'] = XPathPatterns._from_dict( _dict.get('exclude_content')) if 'keep_tag_attributes' in _dict: args['keep_tag_attributes'] = _dict.get('keep_tag_attributes') if 'exclude_tag_attributes' in _dict: args['exclude_tag_attributes'] = _dict.get('exclude_tag_attributes') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'exclude_tags_completely' ) and self.exclude_tags_completely is not None: _dict['exclude_tags_completely'] = self.exclude_tags_completely if hasattr(self, 'exclude_tags_keep_content' ) and self.exclude_tags_keep_content is not None: _dict['exclude_tags_keep_content'] = self.exclude_tags_keep_content if hasattr(self, 'keep_content') and self.keep_content is not None: _dict['keep_content'] = self.keep_content._to_dict() if hasattr(self, 'exclude_content') and self.exclude_content is not None: _dict['exclude_content'] = self.exclude_content._to_dict() if hasattr( self, 'keep_tag_attributes') and self.keep_tag_attributes is not None: _dict['keep_tag_attributes'] = self.keep_tag_attributes if hasattr(self, 'exclude_tag_attributes' ) and self.exclude_tag_attributes is not None: _dict['exclude_tag_attributes'] = self.exclude_tag_attributes return _dict def __str__(self): """Return a `str` version of this HtmlSettings object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IndexCapacity(object): """ Details about the resource usage and capacity of the environment. :attr EnvironmentDocuments documents: (optional) Summary of the document usage statistics for the environment. :attr DiskUsage disk_usage: (optional) Summary of the disk usage statistics for the environment. :attr CollectionUsage collections: (optional) Summary of the collection usage in the environment. :attr MemoryUsage memory_usage: (optional) **Deprecated**: Summary of the memory usage statistics for this environment. """ def __init__(self, documents=None, disk_usage=None, collections=None, memory_usage=None): """ Initialize a IndexCapacity object. :param EnvironmentDocuments documents: (optional) Summary of the document usage statistics for the environment. :param DiskUsage disk_usage: (optional) Summary of the disk usage statistics for the environment. :param CollectionUsage collections: (optional) Summary of the collection usage in the environment. :param MemoryUsage memory_usage: (optional) **Deprecated**: Summary of the memory usage statistics for this environment. """ self.documents = documents self.disk_usage = disk_usage self.collections = collections self.memory_usage = memory_usage @classmethod def _from_dict(cls, _dict): """Initialize a IndexCapacity object from a json dictionary.""" args = {} if 'documents' in _dict: args['documents'] = EnvironmentDocuments._from_dict( _dict.get('documents')) if 'disk_usage' in _dict: args['disk_usage'] = DiskUsage._from_dict(_dict.get('disk_usage')) if 'collections' in _dict: args['collections'] = CollectionUsage._from_dict( _dict.get('collections')) if 'memory_usage' in _dict: args['memory_usage'] = MemoryUsage._from_dict( _dict.get('memory_usage')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: _dict['documents'] = self.documents._to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: _dict['disk_usage'] = self.disk_usage._to_dict() if hasattr(self, 'collections') and self.collections is not None: _dict['collections'] = self.collections._to_dict() if hasattr(self, 'memory_usage') and self.memory_usage is not None: _dict['memory_usage'] = self.memory_usage._to_dict() return _dict def __str__(self): """Return a `str` version of this IndexCapacity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ListCollectionFieldsResponse(object): """ The list of fetched fields. The fields are returned using a fully qualified name format, however, the format differs slightly from that used by the query operations. * Fields which contain nested JSON objects are assigned a type of "nested". * Fields which belong to a nested object are prefixed with `.properties` (for example, `warnings.properties.severity` means that the `warnings` object has a property called `severity`). * Fields returned from the News collection are prefixed with `v{N}-fullnews-t3-{YEAR}.mappings` (for example, `v5-fullnews-t3-2016.mappings.text.properties.author`). :attr list[Field] fields: (optional) An array containing information about each field in the collections. """ def __init__(self, fields=None): """ Initialize a ListCollectionFieldsResponse object. :param list[Field] fields: (optional) An array containing information about each field in the collections. """ self.fields = fields @classmethod def _from_dict(cls, _dict): """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} if 'fields' in _dict: args['fields'] = [ Field._from_dict(x) for x in (_dict.get('fields')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields') and self.fields is not None: _dict['fields'] = [x._to_dict() for x in self.fields] return _dict def __str__(self): """Return a `str` version of this ListCollectionFieldsResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ListCollectionsResponse(object): """ ListCollectionsResponse. :attr list[Collection] collections: (optional) An array containing information about each collection in the environment. """ def __init__(self, collections=None): """ Initialize a ListCollectionsResponse object. :param list[Collection] collections: (optional) An array containing information about each collection in the environment. """ self.collections = collections @classmethod def _from_dict(cls, _dict): """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} if 'collections' in _dict: args['collections'] = [ Collection._from_dict(x) for x in (_dict.get('collections')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict def __str__(self): """Return a `str` version of this ListCollectionsResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ListConfigurationsResponse(object): """ ListConfigurationsResponse. :attr list[Configuration] configurations: (optional) An array of Configurations that are available for the service instance. """ def __init__(self, configurations=None): """ Initialize a ListConfigurationsResponse object. :param list[Configuration] configurations: (optional) An array of Configurations that are available for the service instance. """ self.configurations = configurations @classmethod def _from_dict(cls, _dict): """Initialize a ListConfigurationsResponse object from a json dictionary.""" args = {} if 'configurations' in _dict: args['configurations'] = [ Configuration._from_dict(x) for x in (_dict.get('configurations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configurations') and self.configurations is not None: _dict['configurations'] = [ x._to_dict() for x in self.configurations ] return _dict def __str__(self): """Return a `str` version of this ListConfigurationsResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ListEnvironmentsResponse(object): """ ListEnvironmentsResponse. :attr list[Environment] environments: (optional) An array of [environments] that are available for the service instance. """ def __init__(self, environments=None): """ Initialize a ListEnvironmentsResponse object. :param list[Environment] environments: (optional) An array of [environments] that are available for the service instance. """ self.environments = environments @classmethod def _from_dict(cls, _dict): """Initialize a ListEnvironmentsResponse object from a json dictionary.""" args = {} if 'environments' in _dict: args['environments'] = [ Environment._from_dict(x) for x in (_dict.get('environments')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environments') and self.environments is not None: _dict['environments'] = [x._to_dict() for x in self.environments] return _dict def __str__(self): """Return a `str` version of this ListEnvironmentsResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogQueryResponse(object): """ Object containing results that match the requested **logs** query. :attr int matching_results: (optional) Number of matching results. :attr list[LogQueryResponseResult] results: (optional) """ def __init__(self, matching_results=None, results=None): """ Initialize a LogQueryResponse object. :param int matching_results: (optional) Number of matching results. :param list[LogQueryResponseResult] results: (optional) """ self.matching_results = matching_results self.results = results @classmethod def _from_dict(cls, _dict): """Initialize a LogQueryResponse object from a json dictionary.""" args = {} if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ LogQueryResponseResult._from_dict(x) for x in (_dict.get('results')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] return _dict def __str__(self): """Return a `str` version of this LogQueryResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogQueryResponseResult(object): """ Individual result object for a **logs** query. Each object represents either a query to a Discovery collection or an event that is associated with a query. :attr str environment_id: (optional) The environment ID that is associated with this log entry. :attr str customer_id: (optional) The **customer_id** label that was specified in the header of the query or event API call that corresponds to this log entry. :attr str document_type: (optional) The type of log entry returned. **query** indicates that the log represents the results of a call to the single collection **query** method. **event** indicates that the log represents a call to the **events** API. :attr str natural_language_query: (optional) The value of the **natural_language_query** query parameter that was used to create these results. Only returned with logs of type **query**. **Note:** Other query parameters (such as **filter** or **deduplicate**) might have been used with this query, but are not recorded. :attr LogQueryResponseResultDocuments document_results: (optional) Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. :attr datetime created_timestamp: (optional) Date that the log result was created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. :attr datetime client_timestamp: (optional) Date specified by the user when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned with logs of type **event**. :attr str query_id: (optional) Identifier that corresponds to the **natural_language_query** string used in the original or associated query. All **event** and **query** log entries that have the same original **natural_language_query** string also have them same **query_id**. This field can be used to recall all **event** and **query** log results that have the same original query (**event** logs do not contain the original **natural_language_query** field). :attr str session_token: (optional) Unique identifier (within a 24-hour period) that identifies a single `query` log and any `event` logs that were created for it. **Note:** If the exact same query is run at the exact same time on different days, the **session_token** for those queries might be identical. However, the **created_timestamp** differs. **Note:** Session tokens are case sensitive. To avoid matching on session tokens that are identical except for case, use the exact match operator (`::`) when you query for a specific session token. :attr str collection_id: (optional) The collection ID of the document associated with this event. Only returned with logs of type `event`. :attr int display_rank: (optional) The original display rank of the document associated with this event. Only returned with logs of type `event`. :attr str document_id: (optional) The document ID of the document associated with this event. Only returned with logs of type `event`. :attr str event_type: (optional) The type of event that this object respresents. Possible values are - `query` the log of a query to a collection - `click` the result of a call to the **events** endpoint. :attr str result_type: (optional) The type of result that this **event** is associated with. Only returned with logs of type `event`. """ def __init__(self, environment_id=None, customer_id=None, document_type=None, natural_language_query=None, document_results=None, created_timestamp=None, client_timestamp=None, query_id=None, session_token=None, collection_id=None, display_rank=None, document_id=None, event_type=None, result_type=None): """ Initialize a LogQueryResponseResult object. :param str environment_id: (optional) The environment ID that is associated with this log entry. :param str customer_id: (optional) The **customer_id** label that was specified in the header of the query or event API call that corresponds to this log entry. :param str document_type: (optional) The type of log entry returned. **query** indicates that the log represents the results of a call to the single collection **query** method. **event** indicates that the log represents a call to the **events** API. :param str natural_language_query: (optional) The value of the **natural_language_query** query parameter that was used to create these results. Only returned with logs of type **query**. **Note:** Other query parameters (such as **filter** or **deduplicate**) might have been used with this query, but are not recorded. :param LogQueryResponseResultDocuments document_results: (optional) Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. :param datetime created_timestamp: (optional) Date that the log result was created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. :param datetime client_timestamp: (optional) Date specified by the user when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned with logs of type **event**. :param str query_id: (optional) Identifier that corresponds to the **natural_language_query** string used in the original or associated query. All **event** and **query** log entries that have the same original **natural_language_query** string also have them same **query_id**. This field can be used to recall all **event** and **query** log results that have the same original query (**event** logs do not contain the original **natural_language_query** field). :param str session_token: (optional) Unique identifier (within a 24-hour period) that identifies a single `query` log and any `event` logs that were created for it. **Note:** If the exact same query is run at the exact same time on different days, the **session_token** for those queries might be identical. However, the **created_timestamp** differs. **Note:** Session tokens are case sensitive. To avoid matching on session tokens that are identical except for case, use the exact match operator (`::`) when you query for a specific session token. :param str collection_id: (optional) The collection ID of the document associated with this event. Only returned with logs of type `event`. :param int display_rank: (optional) The original display rank of the document associated with this event. Only returned with logs of type `event`. :param str document_id: (optional) The document ID of the document associated with this event. Only returned with logs of type `event`. :param str event_type: (optional) The type of event that this object respresents. Possible values are - `query` the log of a query to a collection - `click` the result of a call to the **events** endpoint. :param str result_type: (optional) The type of result that this **event** is associated with. Only returned with logs of type `event`. """ self.environment_id = environment_id self.customer_id = customer_id self.document_type = document_type self.natural_language_query = natural_language_query self.document_results = document_results self.created_timestamp = created_timestamp self.client_timestamp = client_timestamp self.query_id = query_id self.session_token = session_token self.collection_id = collection_id self.display_rank = display_rank self.document_id = document_id self.event_type = event_type self.result_type = result_type @classmethod def _from_dict(cls, _dict): """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'customer_id' in _dict: args['customer_id'] = _dict.get('customer_id') if 'document_type' in _dict: args['document_type'] = _dict.get('document_type') if 'natural_language_query' in _dict: args['natural_language_query'] = _dict.get('natural_language_query') if 'document_results' in _dict: args[ 'document_results'] = LogQueryResponseResultDocuments._from_dict( _dict.get('document_results')) if 'created_timestamp' in _dict: args['created_timestamp'] = string_to_datetime( _dict.get('created_timestamp')) if 'client_timestamp' in _dict: args['client_timestamp'] = string_to_datetime( _dict.get('client_timestamp')) if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') if 'session_token' in _dict: args['session_token'] = _dict.get('session_token') if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'display_rank' in _dict: args['display_rank'] = _dict.get('display_rank') if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'event_type' in _dict: args['event_type'] = _dict.get('event_type') if 'result_type' in _dict: args['result_type'] = _dict.get('result_type') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environment_id') and self.environment_id is not None: _dict['environment_id'] = self.environment_id if hasattr(self, 'customer_id') and self.customer_id is not None: _dict['customer_id'] = self.customer_id if hasattr(self, 'document_type') and self.document_type is not None: _dict['document_type'] = self.document_type if hasattr(self, 'natural_language_query' ) and self.natural_language_query is not None: _dict['natural_language_query'] = self.natural_language_query if hasattr(self, 'document_results') and self.document_results is not None: _dict['document_results'] = self.document_results._to_dict() if hasattr(self, 'created_timestamp') and self.created_timestamp is not None: _dict['created_timestamp'] = datetime_to_string( self.created_timestamp) if hasattr(self, 'client_timestamp') and self.client_timestamp is not None: _dict['client_timestamp'] = datetime_to_string( self.client_timestamp) if hasattr(self, 'query_id') and self.query_id is not None: _dict['query_id'] = self.query_id if hasattr(self, 'session_token') and self.session_token is not None: _dict['session_token'] = self.session_token if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'display_rank') and self.display_rank is not None: _dict['display_rank'] = self.display_rank if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'result_type') and self.result_type is not None: _dict['result_type'] = self.result_type return _dict def __str__(self): """Return a `str` version of this LogQueryResponseResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogQueryResponseResultDocuments(object): """ Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. :attr list[LogQueryResponseResultDocumentsResult] results: (optional) :attr int count: (optional) The number of results returned in the query associate with this log. """ def __init__(self, results=None, count=None): """ Initialize a LogQueryResponseResultDocuments object. :param list[LogQueryResponseResultDocumentsResult] results: (optional) :param int count: (optional) The number of results returned in the query associate with this log. """ self.results = results self.count = count @classmethod def _from_dict(cls, _dict): """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} if 'results' in _dict: args['results'] = [ LogQueryResponseResultDocumentsResult._from_dict(x) for x in (_dict.get('results')) ] if 'count' in _dict: args['count'] = _dict.get('count') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count return _dict def __str__(self): """Return a `str` version of this LogQueryResponseResultDocuments object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogQueryResponseResultDocumentsResult(object): """ Each object in the **results** array corresponds to an individual document returned by the original query. :attr int position: (optional) The result rank of this document. A position of `1` indicates that it was the first returned result. :attr str document_id: (optional) The **document_id** of the document that this result represents. :attr float score: (optional) The raw score of this result. A higher score indicates a greater match to the query parameters. :attr float confidence: (optional) The confidence score of the result's analysis. A higher score indicating greater confidence. :attr str collection_id: (optional) The **collection_id** of the document represented by this result. """ def __init__(self, position=None, document_id=None, score=None, confidence=None, collection_id=None): """ Initialize a LogQueryResponseResultDocumentsResult object. :param int position: (optional) The result rank of this document. A position of `1` indicates that it was the first returned result. :param str document_id: (optional) The **document_id** of the document that this result represents. :param float score: (optional) The raw score of this result. A higher score indicates a greater match to the query parameters. :param float confidence: (optional) The confidence score of the result's analysis. A higher score indicating greater confidence. :param str collection_id: (optional) The **collection_id** of the document represented by this result. """ self.position = position self.document_id = document_id self.score = score self.confidence = confidence self.collection_id = collection_id @classmethod def _from_dict(cls, _dict): """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" args = {} if 'position' in _dict: args['position'] = _dict.get('position') if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'score' in _dict: args['score'] = _dict.get('score') if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'position') and self.position is not None: _dict['position'] = self.position if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id return _dict def __str__(self): """Return a `str` version of this LogQueryResponseResultDocumentsResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MemoryUsage(object): """ **Deprecated**: Summary of the memory usage statistics for this environment. :attr int used_bytes: (optional) **Deprecated**: Number of bytes used in the environment's memory capacity. :attr int total_bytes: (optional) **Deprecated**: Total number of bytes available in the environment's memory capacity. :attr str used: (optional) **Deprecated**: Amount of memory capacity used, in KB or GB format. :attr str total: (optional) **Deprecated**: Total amount of the environment's memory capacity, in KB or GB format. :attr float percent_used: (optional) **Deprecated**: Percentage of the environment's memory capacity that is being used. """ def __init__(self, used_bytes=None, total_bytes=None, used=None, total=None, percent_used=None): """ Initialize a MemoryUsage object. :param int used_bytes: (optional) **Deprecated**: Number of bytes used in the environment's memory capacity. :param int total_bytes: (optional) **Deprecated**: Total number of bytes available in the environment's memory capacity. :param str used: (optional) **Deprecated**: Amount of memory capacity used, in KB or GB format. :param str total: (optional) **Deprecated**: Total amount of the environment's memory capacity, in KB or GB format. :param float percent_used: (optional) **Deprecated**: Percentage of the environment's memory capacity that is being used. """ self.used_bytes = used_bytes self.total_bytes = total_bytes self.used = used self.total = total self.percent_used = percent_used @classmethod def _from_dict(cls, _dict): """Initialize a MemoryUsage object from a json dictionary.""" args = {} if 'used_bytes' in _dict: args['used_bytes'] = _dict.get('used_bytes') if 'total_bytes' in _dict: args['total_bytes'] = _dict.get('total_bytes') if 'used' in _dict: args['used'] = _dict.get('used') if 'total' in _dict: args['total'] = _dict.get('total') if 'percent_used' in _dict: args['percent_used'] = _dict.get('percent_used') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'used_bytes') and self.used_bytes is not None: _dict['used_bytes'] = self.used_bytes if hasattr(self, 'total_bytes') and self.total_bytes is not None: _dict['total_bytes'] = self.total_bytes if hasattr(self, 'used') and self.used is not None: _dict['used'] = self.used if hasattr(self, 'total') and self.total is not None: _dict['total'] = self.total if hasattr(self, 'percent_used') and self.percent_used is not None: _dict['percent_used'] = self.percent_used return _dict def __str__(self): """Return a `str` version of this MemoryUsage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetricAggregation(object): """ An aggregation analyzing log information for queries and events. :attr str interval: (optional) The measurement interval for this metric. Metric intervals are always 1 day (`1d`). :attr str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. :attr list[MetricAggregationResult] results: (optional) """ def __init__(self, interval=None, event_type=None, results=None): """ Initialize a MetricAggregation object. :param str interval: (optional) The measurement interval for this metric. Metric intervals are always 1 day (`1d`). :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. :param list[MetricAggregationResult] results: (optional) """ self.interval = interval self.event_type = event_type self.results = results @classmethod def _from_dict(cls, _dict): """Initialize a MetricAggregation object from a json dictionary.""" args = {} if 'interval' in _dict: args['interval'] = _dict.get('interval') if 'event_type' in _dict: args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ MetricAggregationResult._from_dict(x) for x in (_dict.get('results')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'interval') and self.interval is not None: _dict['interval'] = self.interval if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] return _dict def __str__(self): """Return a `str` version of this MetricAggregation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetricAggregationResult(object): """ Aggregation result data for the requested metric. :attr datetime key_as_string: (optional) Date in string form representing the start of this interval. :attr int key: (optional) Unix epoch time equivalent of the **key_as_string**, that represents the start of this interval. :attr int matching_results: (optional) Number of matching results. :attr float event_rate: (optional) The number of queries with associated events divided by the total number of queries for the interval. Only returned with **event_rate** metrics. """ def __init__(self, key_as_string=None, key=None, matching_results=None, event_rate=None): """ Initialize a MetricAggregationResult object. :param datetime key_as_string: (optional) Date in string form representing the start of this interval. :param int key: (optional) Unix epoch time equivalent of the **key_as_string**, that represents the start of this interval. :param int matching_results: (optional) Number of matching results. :param float event_rate: (optional) The number of queries with associated events divided by the total number of queries for the interval. Only returned with **event_rate** metrics. """ self.key_as_string = key_as_string self.key = key self.matching_results = matching_results self.event_rate = event_rate @classmethod def _from_dict(cls, _dict): """Initialize a MetricAggregationResult object from a json dictionary.""" args = {} if 'key_as_string' in _dict: args['key_as_string'] = string_to_datetime( _dict.get('key_as_string')) if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'event_rate' in _dict: args['event_rate'] = _dict.get('event_rate') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key_as_string') and self.key_as_string is not None: _dict['key_as_string'] = datetime_to_string(self.key_as_string) if hasattr(self, 'key') and self.key is not None: _dict['key'] = self.key if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'event_rate') and self.event_rate is not None: _dict['event_rate'] = self.event_rate return _dict def __str__(self): """Return a `str` version of this MetricAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetricResponse(object): """ The response generated from a call to a **metrics** method. :attr list[MetricAggregation] aggregations: (optional) """ def __init__(self, aggregations=None): """ Initialize a MetricResponse object. :param list[MetricAggregation] aggregations: (optional) """ self.aggregations = aggregations @classmethod def _from_dict(cls, _dict): """Initialize a MetricResponse object from a json dictionary.""" args = {} if 'aggregations' in _dict: args['aggregations'] = [ MetricAggregation._from_dict(x) for x in (_dict.get('aggregations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict def __str__(self): """Return a `str` version of this MetricResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetricTokenAggregation(object): """ An aggregation analyzing log information for queries and events. :attr str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. :attr list[MetricTokenAggregationResult] results: (optional) """ def __init__(self, event_type=None, results=None): """ Initialize a MetricTokenAggregation object. :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. :param list[MetricTokenAggregationResult] results: (optional) """ self.event_type = event_type self.results = results @classmethod def _from_dict(cls, _dict): """Initialize a MetricTokenAggregation object from a json dictionary.""" args = {} if 'event_type' in _dict: args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ MetricTokenAggregationResult._from_dict(x) for x in (_dict.get('results')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] return _dict def __str__(self): """Return a `str` version of this MetricTokenAggregation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetricTokenAggregationResult(object): """ Aggregation result data for the requested metric. :attr str key: (optional) The content of the **natural_language_query** parameter used in the query that this result represents. :attr int matching_results: (optional) Number of matching results. :attr float event_rate: (optional) The number of queries with associated events divided by the total number of queries currently stored (queries and events are stored in the log for 30 days). """ def __init__(self, key=None, matching_results=None, event_rate=None): """ Initialize a MetricTokenAggregationResult object. :param str key: (optional) The content of the **natural_language_query** parameter used in the query that this result represents. :param int matching_results: (optional) Number of matching results. :param float event_rate: (optional) The number of queries with associated events divided by the total number of queries currently stored (queries and events are stored in the log for 30 days). """ self.key = key self.matching_results = matching_results self.event_rate = event_rate @classmethod def _from_dict(cls, _dict): """Initialize a MetricTokenAggregationResult object from a json dictionary.""" args = {} if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'event_rate' in _dict: args['event_rate'] = _dict.get('event_rate') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: _dict['key'] = self.key if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'event_rate') and self.event_rate is not None: _dict['event_rate'] = self.event_rate return _dict def __str__(self): """Return a `str` version of this MetricTokenAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetricTokenResponse(object): """ The response generated from a call to a **metrics** method that evaluates tokens. :attr list[MetricTokenAggregation] aggregations: (optional) """ def __init__(self, aggregations=None): """ Initialize a MetricTokenResponse object. :param list[MetricTokenAggregation] aggregations: (optional) """ self.aggregations = aggregations @classmethod def _from_dict(cls, _dict): """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} if 'aggregations' in _dict: args['aggregations'] = [ MetricTokenAggregation._from_dict(x) for x in (_dict.get('aggregations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict def __str__(self): """Return a `str` version of this MetricTokenResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentCategories(object): """ An object that indicates the Categories enrichment will be applied to the specified field. """ def __init__(self, **kwargs): """ Initialize a NluEnrichmentCategories object. :param **kwargs: (optional) Any additional properties. """ for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentCategories object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {} if not hasattr(self, '_additionalProperties'): super(NluEnrichmentCategories, self).__setattr__( '_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(NluEnrichmentCategories, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this NluEnrichmentCategories object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentConcepts(object): """ An object specifiying the concepts enrichment and related parameters. :attr int limit: (optional) The maximum number of concepts enrichments to extact from each instance of the specified field. """ def __init__(self, limit=None): """ Initialize a NluEnrichmentConcepts object. :param int limit: (optional) The maximum number of concepts enrichments to extact from each instance of the specified field. """ self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentConcepts object from a json dictionary.""" args = {} if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this NluEnrichmentConcepts object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentEmotion(object): """ An object specifying the emotion detection enrichment and related parameters. :attr bool document: (optional) When `true`, emotion detection is performed on the entire field. :attr list[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ def __init__(self, document=None, targets=None): """ Initialize a NluEnrichmentEmotion object. :param bool document: (optional) When `true`, emotion detection is performed on the entire field. :param list[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ self.document = document self.targets = targets @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentEmotion object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: args['targets'] = _dict.get('targets') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets return _dict def __str__(self): """Return a `str` version of this NluEnrichmentEmotion object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentEntities(object): """ An object speficying the Entities enrichment and related parameters. :attr bool sentiment: (optional) When `true`, sentiment analysis of entities will be performed on the specified field. :attr bool emotion: (optional) When `true`, emotion detection of entities will be performed on the specified field. :attr int limit: (optional) The maximum number of entities to extract for each instance of the specified field. :attr bool mentions: (optional) When `true`, the number of mentions of each identified entity is recorded. The default is `false`. :attr bool mention_types: (optional) When `true`, the types of mentions for each idetifieid entity is recorded. The default is `false`. :attr bool sentence_locations: (optional) When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. :attr str model: (optional) The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, or the default public model `alchemy`. """ def __init__(self, sentiment=None, emotion=None, limit=None, mentions=None, mention_types=None, sentence_locations=None, model=None): """ Initialize a NluEnrichmentEntities object. :param bool sentiment: (optional) When `true`, sentiment analysis of entities will be performed on the specified field. :param bool emotion: (optional) When `true`, emotion detection of entities will be performed on the specified field. :param int limit: (optional) The maximum number of entities to extract for each instance of the specified field. :param bool mentions: (optional) When `true`, the number of mentions of each identified entity is recorded. The default is `false`. :param bool mention_types: (optional) When `true`, the types of mentions for each idetifieid entity is recorded. The default is `false`. :param bool sentence_locations: (optional) When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. :param str model: (optional) The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, or the default public model `alchemy`. """ self.sentiment = sentiment self.emotion = emotion self.limit = limit self.mentions = mentions self.mention_types = mention_types self.sentence_locations = sentence_locations self.model = model @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentEntities object from a json dictionary.""" args = {} if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: args['emotion'] = _dict.get('emotion') if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'mentions' in _dict: args['mentions'] = _dict.get('mentions') if 'mention_types' in _dict: args['mention_types'] = _dict.get('mention_types') if 'sentence_locations' in _dict: args['sentence_locations'] = _dict.get('sentence_locations') if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit if hasattr(self, 'mentions') and self.mentions is not None: _dict['mentions'] = self.mentions if hasattr(self, 'mention_types') and self.mention_types is not None: _dict['mention_types'] = self.mention_types if hasattr( self, 'sentence_locations') and self.sentence_locations is not None: _dict['sentence_locations'] = self.sentence_locations if hasattr(self, 'model') and self.model is not None: _dict['model'] = self.model return _dict def __str__(self): """Return a `str` version of this NluEnrichmentEntities object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentFeatures(object): """ NluEnrichmentFeatures. :attr NluEnrichmentKeywords keywords: (optional) An object specifying the Keyword enrichment and related parameters. :attr NluEnrichmentEntities entities: (optional) An object speficying the Entities enrichment and related parameters. :attr NluEnrichmentSentiment sentiment: (optional) An object specifying the sentiment extraction enrichment and related parameters. :attr NluEnrichmentEmotion emotion: (optional) An object specifying the emotion detection enrichment and related parameters. :attr NluEnrichmentCategories categories: (optional) An object that indicates the Categories enrichment will be applied to the specified field. :attr NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying the semantic roles enrichment and related parameters. :attr NluEnrichmentRelations relations: (optional) An object specifying the relations enrichment and related parameters. :attr NluEnrichmentConcepts concepts: (optional) An object specifiying the concepts enrichment and related parameters. """ def __init__(self, keywords=None, entities=None, sentiment=None, emotion=None, categories=None, semantic_roles=None, relations=None, concepts=None): """ Initialize a NluEnrichmentFeatures object. :param NluEnrichmentKeywords keywords: (optional) An object specifying the Keyword enrichment and related parameters. :param NluEnrichmentEntities entities: (optional) An object speficying the Entities enrichment and related parameters. :param NluEnrichmentSentiment sentiment: (optional) An object specifying the sentiment extraction enrichment and related parameters. :param NluEnrichmentEmotion emotion: (optional) An object specifying the emotion detection enrichment and related parameters. :param NluEnrichmentCategories categories: (optional) An object that indicates the Categories enrichment will be applied to the specified field. :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying the semantic roles enrichment and related parameters. :param NluEnrichmentRelations relations: (optional) An object specifying the relations enrichment and related parameters. :param NluEnrichmentConcepts concepts: (optional) An object specifiying the concepts enrichment and related parameters. """ self.keywords = keywords self.entities = entities self.sentiment = sentiment self.emotion = emotion self.categories = categories self.semantic_roles = semantic_roles self.relations = relations self.concepts = concepts @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentFeatures object from a json dictionary.""" args = {} if 'keywords' in _dict: args['keywords'] = NluEnrichmentKeywords._from_dict( _dict.get('keywords')) if 'entities' in _dict: args['entities'] = NluEnrichmentEntities._from_dict( _dict.get('entities')) if 'sentiment' in _dict: args['sentiment'] = NluEnrichmentSentiment._from_dict( _dict.get('sentiment')) if 'emotion' in _dict: args['emotion'] = NluEnrichmentEmotion._from_dict( _dict.get('emotion')) if 'categories' in _dict: args['categories'] = NluEnrichmentCategories._from_dict( _dict.get('categories')) if 'semantic_roles' in _dict: args['semantic_roles'] = NluEnrichmentSemanticRoles._from_dict( _dict.get('semantic_roles')) if 'relations' in _dict: args['relations'] = NluEnrichmentRelations._from_dict( _dict.get('relations')) if 'concepts' in _dict: args['concepts'] = NluEnrichmentConcepts._from_dict( _dict.get('concepts')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = self.keywords._to_dict() if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = self.entities._to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment._to_dict() if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = self.categories._to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: _dict['semantic_roles'] = self.semantic_roles._to_dict() if hasattr(self, 'relations') and self.relations is not None: _dict['relations'] = self.relations._to_dict() if hasattr(self, 'concepts') and self.concepts is not None: _dict['concepts'] = self.concepts._to_dict() return _dict def __str__(self): """Return a `str` version of this NluEnrichmentFeatures object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentKeywords(object): """ An object specifying the Keyword enrichment and related parameters. :attr bool sentiment: (optional) When `true`, sentiment analysis of keywords will be performed on the specified field. :attr bool emotion: (optional) When `true`, emotion detection of keywords will be performed on the specified field. :attr int limit: (optional) The maximum number of keywords to extract for each instance of the specified field. """ def __init__(self, sentiment=None, emotion=None, limit=None): """ Initialize a NluEnrichmentKeywords object. :param bool sentiment: (optional) When `true`, sentiment analysis of keywords will be performed on the specified field. :param bool emotion: (optional) When `true`, emotion detection of keywords will be performed on the specified field. :param int limit: (optional) The maximum number of keywords to extract for each instance of the specified field. """ self.sentiment = sentiment self.emotion = emotion self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentKeywords object from a json dictionary.""" args = {} if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: args['emotion'] = _dict.get('emotion') if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this NluEnrichmentKeywords object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentRelations(object): """ An object specifying the relations enrichment and related parameters. :attr str model: (optional) *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with relationship extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, the default is`en-news`. """ def __init__(self, model=None): """ Initialize a NluEnrichmentRelations object. :param str model: (optional) *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with relationship extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, the default is`en-news`. """ self.model = model @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentRelations object from a json dictionary.""" args = {} if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'model') and self.model is not None: _dict['model'] = self.model return _dict def __str__(self): """Return a `str` version of this NluEnrichmentRelations object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentSemanticRoles(object): """ An object specifiying the semantic roles enrichment and related parameters. :attr bool entities: (optional) When `true`, entities are extracted from the identified sentence parts. :attr bool keywords: (optional) When `true`, keywords are extracted from the identified sentence parts. :attr int limit: (optional) The maximum number of semantic roles enrichments to extact from each instance of the specified field. """ def __init__(self, entities=None, keywords=None, limit=None): """ Initialize a NluEnrichmentSemanticRoles object. :param bool entities: (optional) When `true`, entities are extracted from the identified sentence parts. :param bool keywords: (optional) When `true`, keywords are extracted from the identified sentence parts. :param int limit: (optional) The maximum number of semantic roles enrichments to extact from each instance of the specified field. """ self.entities = entities self.keywords = keywords self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" args = {} if 'entities' in _dict: args['entities'] = _dict.get('entities') if 'keywords' in _dict: args['keywords'] = _dict.get('keywords') if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = self.entities if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = self.keywords if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this NluEnrichmentSemanticRoles object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NluEnrichmentSentiment(object): """ An object specifying the sentiment extraction enrichment and related parameters. :attr bool document: (optional) When `true`, sentiment analysis is performed on the entire field. :attr list[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ def __init__(self, document=None, targets=None): """ Initialize a NluEnrichmentSentiment object. :param bool document: (optional) When `true`, sentiment analysis is performed on the entire field. :param list[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ self.document = document self.targets = targets @classmethod def _from_dict(cls, _dict): """Initialize a NluEnrichmentSentiment object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: args['targets'] = _dict.get('targets') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets return _dict def __str__(self): """Return a `str` version of this NluEnrichmentSentiment object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class NormalizationOperation(object): """ NormalizationOperation. :attr str operation: (optional) Identifies what type of operation to perform. **copy** - Copies the value of the **source_field** to the **destination_field** field. If the **destination_field** already exists, then the value of the **source_field** overwrites the original value of the **destination_field**. **move** - Renames (moves) the **source_field** to the **destination_field**. If the **destination_field** already exists, then the value of the **source_field** overwrites the original value of the **destination_field**. Rename is identical to copy, except that the **source_field** is removed after the value has been copied to the **destination_field** (it is the same as a _copy_ followed by a _remove_). **merge** - Merges the value of the **source_field** with the value of the **destination_field**. The **destination_field** is converted into an array if it is not already an array, and the value of the **source_field** is appended to the array. This operation removes the **source_field** after the merge. If the **source_field** does not exist in the current document, then the **destination_field** is still converted into an array (if it is not an array already). This conversion ensures the type for **destination_field** is consistent across all documents. **remove** - Deletes the **source_field** field. The **destination_field** is ignored for this operation. **remove_nulls** - Removes all nested null (blank) field values from the JSON tree. **source_field** and **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire JSON tree. Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be time-expensive). :attr str source_field: (optional) The source field for the operation. :attr str destination_field: (optional) The destination field for the operation. """ def __init__(self, operation=None, source_field=None, destination_field=None): """ Initialize a NormalizationOperation object. :param str operation: (optional) Identifies what type of operation to perform. **copy** - Copies the value of the **source_field** to the **destination_field** field. If the **destination_field** already exists, then the value of the **source_field** overwrites the original value of the **destination_field**. **move** - Renames (moves) the **source_field** to the **destination_field**. If the **destination_field** already exists, then the value of the **source_field** overwrites the original value of the **destination_field**. Rename is identical to copy, except that the **source_field** is removed after the value has been copied to the **destination_field** (it is the same as a _copy_ followed by a _remove_). **merge** - Merges the value of the **source_field** with the value of the **destination_field**. The **destination_field** is converted into an array if it is not already an array, and the value of the **source_field** is appended to the array. This operation removes the **source_field** after the merge. If the **source_field** does not exist in the current document, then the **destination_field** is still converted into an array (if it is not an array already). This conversion ensures the type for **destination_field** is consistent across all documents. **remove** - Deletes the **source_field** field. The **destination_field** is ignored for this operation. **remove_nulls** - Removes all nested null (blank) field values from the JSON tree. **source_field** and **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire JSON tree. Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be time-expensive). :param str source_field: (optional) The source field for the operation. :param str destination_field: (optional) The destination field for the operation. """ self.operation = operation self.source_field = source_field self.destination_field = destination_field @classmethod def _from_dict(cls, _dict): """Initialize a NormalizationOperation object from a json dictionary.""" args = {} if 'operation' in _dict: args['operation'] = _dict.get('operation') if 'source_field' in _dict: args['source_field'] = _dict.get('source_field') if 'destination_field' in _dict: args['destination_field'] = _dict.get('destination_field') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'operation') and self.operation is not None: _dict['operation'] = self.operation if hasattr(self, 'source_field') and self.source_field is not None: _dict['source_field'] = self.source_field if hasattr(self, 'destination_field') and self.destination_field is not None: _dict['destination_field'] = self.destination_field return _dict def __str__(self): """Return a `str` version of this NormalizationOperation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Notice(object): """ A notice produced for the collection. :attr str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. :attr datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str document_id: (optional) Unique identifier of the document. :attr str query_id: (optional) Unique identifier of the query used for relevance training. :attr str severity: (optional) Severity level of the notice. :attr str step: (optional) Ingestion or training step in which the notice occurred. :attr str description: (optional) The description of the notice. """ def __init__(self, notice_id=None, created=None, document_id=None, query_id=None, severity=None, step=None, description=None): """ Initialize a Notice object. :param str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str document_id: (optional) Unique identifier of the document. :param str query_id: (optional) Unique identifier of the query used for relevance training. :param str severity: (optional) Severity level of the notice. :param str step: (optional) Ingestion or training step in which the notice occurred. :param str description: (optional) The description of the notice. """ self.notice_id = notice_id self.created = created self.document_id = document_id self.query_id = query_id self.severity = severity self.step = step self.description = description @classmethod def _from_dict(cls, _dict): """Initialize a Notice object from a json dictionary.""" args = {} if 'notice_id' in _dict: args['notice_id'] = _dict.get('notice_id') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') if 'severity' in _dict: args['severity'] = _dict.get('severity') if 'step' in _dict: args['step'] = _dict.get('step') if 'description' in _dict: args['description'] = _dict.get('description') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'notice_id') and self.notice_id is not None: _dict['notice_id'] = self.notice_id if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'query_id') and self.query_id is not None: _dict['query_id'] = self.query_id if hasattr(self, 'severity') and self.severity is not None: _dict['severity'] = self.severity if hasattr(self, 'step') and self.step is not None: _dict['step'] = self.step if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict def __str__(self): """Return a `str` version of this Notice object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class PdfHeadingDetection(object): """ PdfHeadingDetection. :attr list[FontSetting] fonts: (optional) """ def __init__(self, fonts=None): """ Initialize a PdfHeadingDetection object. :param list[FontSetting] fonts: (optional) """ self.fonts = fonts @classmethod def _from_dict(cls, _dict): """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} if 'fonts' in _dict: args['fonts'] = [ FontSetting._from_dict(x) for x in (_dict.get('fonts')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: _dict['fonts'] = [x._to_dict() for x in self.fonts] return _dict def __str__(self): """Return a `str` version of this PdfHeadingDetection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class PdfSettings(object): """ A list of PDF conversion settings. :attr PdfHeadingDetection heading: (optional) """ def __init__(self, heading=None): """ Initialize a PdfSettings object. :param PdfHeadingDetection heading: (optional) """ self.heading = heading @classmethod def _from_dict(cls, _dict): """Initialize a PdfSettings object from a json dictionary.""" args = {} if 'heading' in _dict: args['heading'] = PdfHeadingDetection._from_dict( _dict.get('heading')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: _dict['heading'] = self.heading._to_dict() return _dict def __str__(self): """Return a `str` version of this PdfSettings object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryAggregation(object): """ An aggregation produced by the Discovery service to analyze the input provided. :attr str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :attr list[AggregationResult] results: (optional) :attr int matching_results: (optional) Number of matching results. :attr list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None): """ Initialize a QueryAggregation object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. """ self.type = type self.results = results self.matching_results = matching_results self.aggregations = aggregations @classmethod def _from_dict(cls, _dict): """Initialize a QueryAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ AggregationResult._from_dict(x) for x in (_dict.get('results')) ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation._from_dict(x) for x in (_dict.get('aggregations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict def __str__(self): """Return a `str` version of this QueryAggregation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryEntitiesContext(object): """ Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`. :attr str text: (optional) Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`. """ def __init__(self, text=None): """ Initialize a QueryEntitiesContext object. :param str text: (optional) Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`. """ self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a QueryEntitiesContext object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this QueryEntitiesContext object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryEntitiesEntity(object): """ A text string that appears within the entity text field. :attr str text: (optional) Entity text content. :attr str type: (optional) The type of the specified entity. """ def __init__(self, text=None, type=None): """ Initialize a QueryEntitiesEntity object. :param str text: (optional) Entity text content. :param str type: (optional) The type of the specified entity. """ self.text = text self.type = type @classmethod def _from_dict(cls, _dict): """Initialize a QueryEntitiesEntity object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'type' in _dict: args['type'] = _dict.get('type') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type return _dict def __str__(self): """Return a `str` version of this QueryEntitiesEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryEntitiesResponse(object): """ An array of entities resulting from the query. :attr list[QueryEntitiesResponseItem] entities: (optional) """ def __init__(self, entities=None): """ Initialize a QueryEntitiesResponse object. :param list[QueryEntitiesResponseItem] entities: (optional) """ self.entities = entities @classmethod def _from_dict(cls, _dict): """Initialize a QueryEntitiesResponse object from a json dictionary.""" args = {} if 'entities' in _dict: args['entities'] = [ QueryEntitiesResponseItem._from_dict(x) for x in (_dict.get('entities')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] return _dict def __str__(self): """Return a `str` version of this QueryEntitiesResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryEntitiesResponseItem(object): """ Object containing Entity query response information. :attr str text: (optional) Entity text content. :attr str type: (optional) The type of the result entity. :attr list[QueryEvidence] evidence: (optional) List of different evidentiary items to support the result. """ def __init__(self, text=None, type=None, evidence=None): """ Initialize a QueryEntitiesResponseItem object. :param str text: (optional) Entity text content. :param str type: (optional) The type of the result entity. :param list[QueryEvidence] evidence: (optional) List of different evidentiary items to support the result. """ self.text = text self.type = type self.evidence = evidence @classmethod def _from_dict(cls, _dict): """Initialize a QueryEntitiesResponseItem object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'type' in _dict: args['type'] = _dict.get('type') if 'evidence' in _dict: args['evidence'] = [ QueryEvidence._from_dict(x) for x in (_dict.get('evidence')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'evidence') and self.evidence is not None: _dict['evidence'] = [x._to_dict() for x in self.evidence] return _dict def __str__(self): """Return a `str` version of this QueryEntitiesResponseItem object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryEvidence(object): """ Description of evidence location supporting Knoweldge Graph query result. :attr str document_id: (optional) The docuemnt ID (as indexed in Discovery) of the evidence location. :attr str field: (optional) The field of the document where the supporting evidence was identified. :attr int start_offset: (optional) The start location of the evidence in the identified field. This value is inclusive. :attr int end_offset: (optional) The end location of the evidence in the identified field. This value is inclusive. :attr list[QueryEvidenceEntity] entities: (optional) An array of entity objects that show evidence of the result. """ def __init__(self, document_id=None, field=None, start_offset=None, end_offset=None, entities=None): """ Initialize a QueryEvidence object. :param str document_id: (optional) The docuemnt ID (as indexed in Discovery) of the evidence location. :param str field: (optional) The field of the document where the supporting evidence was identified. :param int start_offset: (optional) The start location of the evidence in the identified field. This value is inclusive. :param int end_offset: (optional) The end location of the evidence in the identified field. This value is inclusive. :param list[QueryEvidenceEntity] entities: (optional) An array of entity objects that show evidence of the result. """ self.document_id = document_id self.field = field self.start_offset = start_offset self.end_offset = end_offset self.entities = entities @classmethod def _from_dict(cls, _dict): """Initialize a QueryEvidence object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'field' in _dict: args['field'] = _dict.get('field') if 'start_offset' in _dict: args['start_offset'] = _dict.get('start_offset') if 'end_offset' in _dict: args['end_offset'] = _dict.get('end_offset') if 'entities' in _dict: args['entities'] = [ QueryEvidenceEntity._from_dict(x) for x in (_dict.get('entities')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'start_offset') and self.start_offset is not None: _dict['start_offset'] = self.start_offset if hasattr(self, 'end_offset') and self.end_offset is not None: _dict['end_offset'] = self.end_offset if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] return _dict def __str__(self): """Return a `str` version of this QueryEvidence object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryEvidenceEntity(object): """ Entity description and location within evidence field. :attr str type: (optional) The entity type for this entity. Possible types vary based on model used. :attr str text: (optional) The original text of this entity as found in the evidence field. :attr int start_offset: (optional) The start location of the entity text in the identified field. This value is inclusive. :attr int end_offset: (optional) The end location of the entity text in the identified field. This value is exclusive. """ def __init__(self, type=None, text=None, start_offset=None, end_offset=None): """ Initialize a QueryEvidenceEntity object. :param str type: (optional) The entity type for this entity. Possible types vary based on model used. :param str text: (optional) The original text of this entity as found in the evidence field. :param int start_offset: (optional) The start location of the entity text in the identified field. This value is inclusive. :param int end_offset: (optional) The end location of the entity text in the identified field. This value is exclusive. """ self.type = type self.text = text self.start_offset = start_offset self.end_offset = end_offset @classmethod def _from_dict(cls, _dict): """Initialize a QueryEvidenceEntity object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: args['text'] = _dict.get('text') if 'start_offset' in _dict: args['start_offset'] = _dict.get('start_offset') if 'end_offset' in _dict: args['end_offset'] = _dict.get('end_offset') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'start_offset') and self.start_offset is not None: _dict['start_offset'] = self.start_offset if hasattr(self, 'end_offset') and self.end_offset is not None: _dict['end_offset'] = self.end_offset return _dict def __str__(self): """Return a `str` version of this QueryEvidenceEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryFilterType(object): """ QueryFilterType. :attr list[str] exclude: (optional) A comma-separated list of types to exclude. :attr list[str] include: (optional) A comma-separated list of types to include. All other types are excluded. """ def __init__(self, exclude=None, include=None): """ Initialize a QueryFilterType object. :param list[str] exclude: (optional) A comma-separated list of types to exclude. :param list[str] include: (optional) A comma-separated list of types to include. All other types are excluded. """ self.exclude = exclude self.include = include @classmethod def _from_dict(cls, _dict): """Initialize a QueryFilterType object from a json dictionary.""" args = {} if 'exclude' in _dict: args['exclude'] = _dict.get('exclude') if 'include' in _dict: args['include'] = _dict.get('include') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'exclude') and self.exclude is not None: _dict['exclude'] = self.exclude if hasattr(self, 'include') and self.include is not None: _dict['include'] = self.include return _dict def __str__(self): """Return a `str` version of this QueryFilterType object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryNoticesResponse(object): """ QueryNoticesResponse. :attr int matching_results: (optional) :attr list[QueryNoticesResult] results: (optional) :attr list[QueryAggregation] aggregations: (optional) :attr list[QueryPassages] passages: (optional) :attr int duplicates_removed: (optional) """ def __init__(self, matching_results=None, results=None, aggregations=None, passages=None, duplicates_removed=None): """ Initialize a QueryNoticesResponse object. :param int matching_results: (optional) :param list[QueryNoticesResult] results: (optional) :param list[QueryAggregation] aggregations: (optional) :param list[QueryPassages] passages: (optional) :param int duplicates_removed: (optional) """ self.matching_results = matching_results self.results = results self.aggregations = aggregations self.passages = passages self.duplicates_removed = duplicates_removed @classmethod def _from_dict(cls, _dict): """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ QueryNoticesResult._from_dict(x) for x in (_dict.get('results')) ] if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation._from_dict(x) for x in (_dict.get('aggregations')) ] if 'passages' in _dict: args['passages'] = [ QueryPassages._from_dict(x) for x in (_dict.get('passages')) ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] if hasattr(self, 'passages') and self.passages is not None: _dict['passages'] = [x._to_dict() for x in self.passages] if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: _dict['duplicates_removed'] = self.duplicates_removed return _dict def __str__(self): """Return a `str` version of this QueryNoticesResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryNoticesResult(object): """ QueryNoticesResult. :attr str id: (optional) The unique identifier of the document. :attr float score: (optional) *Deprecated* This field is now part of the **result_metadata** object. :attr object metadata: (optional) Metadata of the document. :attr str collection_id: (optional) The collection ID of the collection containing the document for this result. :attr QueryResultMetadata result_metadata: (optional) Metadata of a query result. :attr int code: (optional) The internal status code returned by the ingestion subsystem indicating the overall result of ingesting the source document. :attr str filename: (optional) Name of the original source file (if available). :attr str file_type: (optional) The type of the original source file. :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). :attr list[Notice] notices: (optional) Array of notices for the document. """ def __init__(self, id=None, score=None, metadata=None, collection_id=None, result_metadata=None, code=None, filename=None, file_type=None, sha1=None, notices=None, **kwargs): """ Initialize a QueryNoticesResult object. :param str id: (optional) The unique identifier of the document. :param float score: (optional) *Deprecated* This field is now part of the **result_metadata** object. :param object metadata: (optional) Metadata of the document. :param str collection_id: (optional) The collection ID of the collection containing the document for this result. :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. :param int code: (optional) The internal status code returned by the ingestion subsystem indicating the overall result of ingesting the source document. :param str filename: (optional) Name of the original source file (if available). :param str file_type: (optional) The type of the original source file. :param str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). :param list[Notice] notices: (optional) Array of notices for the document. :param **kwargs: (optional) Any additional properties. """ self.id = id self.score = score self.metadata = metadata self.collection_id = collection_id self.result_metadata = result_metadata self.code = code self.filename = filename self.file_type = file_type self.sha1 = sha1 self.notices = notices for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a QueryNoticesResult object from a json dictionary.""" args = {} xtra = _dict.copy() if 'id' in _dict: args['id'] = _dict.get('id') del xtra['id'] if 'score' in _dict: args['score'] = _dict.get('score') del xtra['score'] if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') del xtra['metadata'] if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') del xtra['collection_id'] if 'result_metadata' in _dict: args['result_metadata'] = QueryResultMetadata._from_dict( _dict.get('result_metadata')) del xtra['result_metadata'] if 'code' in _dict: args['code'] = _dict.get('code') del xtra['code'] if 'filename' in _dict: args['filename'] = _dict.get('filename') del xtra['filename'] if 'file_type' in _dict: args['file_type'] = _dict.get('file_type') del xtra['file_type'] if 'sha1' in _dict: args['sha1'] = _dict.get('sha1') del xtra['sha1'] if 'notices' in _dict: args['notices'] = [ Notice._from_dict(x) for x in (_dict.get('notices')) ] del xtra['notices'] args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: _dict['result_metadata'] = self.result_metadata._to_dict() if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'file_type') and self.file_type is not None: _dict['file_type'] = self.file_type if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 if hasattr(self, 'notices') and self.notices is not None: _dict['notices'] = [x._to_dict() for x in self.notices] if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = { 'id', 'score', 'metadata', 'collection_id', 'result_metadata', 'code', 'filename', 'file_type', 'sha1', 'notices' } if not hasattr(self, '_additionalProperties'): super(QueryNoticesResult, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(QueryNoticesResult, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this QueryNoticesResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryPassages(object): """ QueryPassages. :attr str document_id: (optional) The unique identifier of the document from which the passage has been extracted. :attr float passage_score: (optional) The confidence score of the passages's analysis. A higher score indicates greater confidence. :attr str passage_text: (optional) The content of the extracted passage. :attr int start_offset: (optional) The position of the first character of the extracted passage in the originating field. :attr int end_offset: (optional) The position of the last character of the extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. """ def __init__(self, document_id=None, passage_score=None, passage_text=None, start_offset=None, end_offset=None, field=None): """ Initialize a QueryPassages object. :param str document_id: (optional) The unique identifier of the document from which the passage has been extracted. :param float passage_score: (optional) The confidence score of the passages's analysis. A higher score indicates greater confidence. :param str passage_text: (optional) The content of the extracted passage. :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. :param int end_offset: (optional) The position of the last character of the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. """ self.document_id = document_id self.passage_score = passage_score self.passage_text = passage_text self.start_offset = start_offset self.end_offset = end_offset self.field = field @classmethod def _from_dict(cls, _dict): """Initialize a QueryPassages object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'passage_score' in _dict: args['passage_score'] = _dict.get('passage_score') if 'passage_text' in _dict: args['passage_text'] = _dict.get('passage_text') if 'start_offset' in _dict: args['start_offset'] = _dict.get('start_offset') if 'end_offset' in _dict: args['end_offset'] = _dict.get('end_offset') if 'field' in _dict: args['field'] = _dict.get('field') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'passage_score') and self.passage_score is not None: _dict['passage_score'] = self.passage_score if hasattr(self, 'passage_text') and self.passage_text is not None: _dict['passage_text'] = self.passage_text if hasattr(self, 'start_offset') and self.start_offset is not None: _dict['start_offset'] = self.start_offset if hasattr(self, 'end_offset') and self.end_offset is not None: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field return _dict def __str__(self): """Return a `str` version of this QueryPassages object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryRelationsArgument(object): """ QueryRelationsArgument. :attr list[QueryEntitiesEntity] entities: (optional) """ def __init__(self, entities=None): """ Initialize a QueryRelationsArgument object. :param list[QueryEntitiesEntity] entities: (optional) """ self.entities = entities @classmethod def _from_dict(cls, _dict): """Initialize a QueryRelationsArgument object from a json dictionary.""" args = {} if 'entities' in _dict: args['entities'] = [ QueryEntitiesEntity._from_dict(x) for x in (_dict.get('entities')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] return _dict def __str__(self): """Return a `str` version of this QueryRelationsArgument object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryRelationsEntity(object): """ QueryRelationsEntity. :attr str text: (optional) Entity text content. :attr str type: (optional) The type of the specified entity. :attr bool exact: (optional) If false, implicit querying is performed. The default is `false`. """ def __init__(self, text=None, type=None, exact=None): """ Initialize a QueryRelationsEntity object. :param str text: (optional) Entity text content. :param str type: (optional) The type of the specified entity. :param bool exact: (optional) If false, implicit querying is performed. The default is `false`. """ self.text = text self.type = type self.exact = exact @classmethod def _from_dict(cls, _dict): """Initialize a QueryRelationsEntity object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'type' in _dict: args['type'] = _dict.get('type') if 'exact' in _dict: args['exact'] = _dict.get('exact') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'exact') and self.exact is not None: _dict['exact'] = self.exact return _dict def __str__(self): """Return a `str` version of this QueryRelationsEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryRelationsFilter(object): """ QueryRelationsFilter. :attr QueryFilterType relation_types: (optional) A list of relation types to include or exclude from the query. :attr QueryFilterType entity_types: (optional) A list of entity types to include or exclude from the query. :attr list[str] document_ids: (optional) A comma-separated list of document IDs to include in the query. """ def __init__(self, relation_types=None, entity_types=None, document_ids=None): """ Initialize a QueryRelationsFilter object. :param QueryFilterType relation_types: (optional) A list of relation types to include or exclude from the query. :param QueryFilterType entity_types: (optional) A list of entity types to include or exclude from the query. :param list[str] document_ids: (optional) A comma-separated list of document IDs to include in the query. """ self.relation_types = relation_types self.entity_types = entity_types self.document_ids = document_ids @classmethod def _from_dict(cls, _dict): """Initialize a QueryRelationsFilter object from a json dictionary.""" args = {} if 'relation_types' in _dict: args['relation_types'] = QueryFilterType._from_dict( _dict.get('relation_types')) if 'entity_types' in _dict: args['entity_types'] = QueryFilterType._from_dict( _dict.get('entity_types')) if 'document_ids' in _dict: args['document_ids'] = _dict.get('document_ids') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'relation_types') and self.relation_types is not None: _dict['relation_types'] = self.relation_types._to_dict() if hasattr(self, 'entity_types') and self.entity_types is not None: _dict['entity_types'] = self.entity_types._to_dict() if hasattr(self, 'document_ids') and self.document_ids is not None: _dict['document_ids'] = self.document_ids return _dict def __str__(self): """Return a `str` version of this QueryRelationsFilter object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryRelationsRelationship(object): """ QueryRelationsRelationship. :attr str type: (optional) The identified relationship type. :attr int frequency: (optional) The number of times the relationship is mentioned. :attr list[QueryRelationsArgument] arguments: (optional) Information about the relationship. :attr list[QueryEvidence] evidence: (optional) List of different evidentiary items to support the result. """ def __init__(self, type=None, frequency=None, arguments=None, evidence=None): """ Initialize a QueryRelationsRelationship object. :param str type: (optional) The identified relationship type. :param int frequency: (optional) The number of times the relationship is mentioned. :param list[QueryRelationsArgument] arguments: (optional) Information about the relationship. :param list[QueryEvidence] evidence: (optional) List of different evidentiary items to support the result. """ self.type = type self.frequency = frequency self.arguments = arguments self.evidence = evidence @classmethod def _from_dict(cls, _dict): """Initialize a QueryRelationsRelationship object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'frequency' in _dict: args['frequency'] = _dict.get('frequency') if 'arguments' in _dict: args['arguments'] = [ QueryRelationsArgument._from_dict(x) for x in (_dict.get('arguments')) ] if 'evidence' in _dict: args['evidence'] = [ QueryEvidence._from_dict(x) for x in (_dict.get('evidence')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'frequency') and self.frequency is not None: _dict['frequency'] = self.frequency if hasattr(self, 'arguments') and self.arguments is not None: _dict['arguments'] = [x._to_dict() for x in self.arguments] if hasattr(self, 'evidence') and self.evidence is not None: _dict['evidence'] = [x._to_dict() for x in self.evidence] return _dict def __str__(self): """Return a `str` version of this QueryRelationsRelationship object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryRelationsResponse(object): """ QueryRelationsResponse. :attr list[QueryRelationsRelationship] relations: (optional) """ def __init__(self, relations=None): """ Initialize a QueryRelationsResponse object. :param list[QueryRelationsRelationship] relations: (optional) """ self.relations = relations @classmethod def _from_dict(cls, _dict): """Initialize a QueryRelationsResponse object from a json dictionary.""" args = {} if 'relations' in _dict: args['relations'] = [ QueryRelationsRelationship._from_dict(x) for x in (_dict.get('relations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'relations') and self.relations is not None: _dict['relations'] = [x._to_dict() for x in self.relations] return _dict def __str__(self): """Return a `str` version of this QueryRelationsResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryResponse(object): """ A response containing the documents and aggregations for the query. :attr int matching_results: (optional) :attr list[QueryResult] results: (optional) :attr list[QueryAggregation] aggregations: (optional) :attr list[QueryPassages] passages: (optional) :attr int duplicates_removed: (optional) :attr str session_token: (optional) The session token for this query. The session token can be used to add events associated with this query to the query and event log. **Important:** Session tokens are case sensitive. :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval type information. """ def __init__(self, matching_results=None, results=None, aggregations=None, passages=None, duplicates_removed=None, session_token=None, retrieval_details=None): """ Initialize a QueryResponse object. :param int matching_results: (optional) :param list[QueryResult] results: (optional) :param list[QueryAggregation] aggregations: (optional) :param list[QueryPassages] passages: (optional) :param int duplicates_removed: (optional) :param str session_token: (optional) The session token for this query. The session token can be used to add events associated with this query to the query and event log. **Important:** Session tokens are case sensitive. :param RetrievalDetails retrieval_details: (optional) An object contain retrieval type information. """ self.matching_results = matching_results self.results = results self.aggregations = aggregations self.passages = passages self.duplicates_removed = duplicates_removed self.session_token = session_token self.retrieval_details = retrieval_details @classmethod def _from_dict(cls, _dict): """Initialize a QueryResponse object from a json dictionary.""" args = {} if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ QueryResult._from_dict(x) for x in (_dict.get('results')) ] if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation._from_dict(x) for x in (_dict.get('aggregations')) ] if 'passages' in _dict: args['passages'] = [ QueryPassages._from_dict(x) for x in (_dict.get('passages')) ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') if 'session_token' in _dict: args['session_token'] = _dict.get('session_token') if 'retrieval_details' in _dict: args['retrieval_details'] = RetrievalDetails._from_dict( _dict.get('retrieval_details')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] if hasattr(self, 'passages') and self.passages is not None: _dict['passages'] = [x._to_dict() for x in self.passages] if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: _dict['duplicates_removed'] = self.duplicates_removed if hasattr(self, 'session_token') and self.session_token is not None: _dict['session_token'] = self.session_token if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: _dict['retrieval_details'] = self.retrieval_details._to_dict() return _dict def __str__(self): """Return a `str` version of this QueryResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryResult(object): """ QueryResult. :attr str id: (optional) The unique identifier of the document. :attr float score: (optional) *Deprecated* This field is now part of the **result_metadata** object. :attr object metadata: (optional) Metadata of the document. :attr str collection_id: (optional) The collection ID of the collection containing the document for this result. :attr QueryResultMetadata result_metadata: (optional) Metadata of a query result. """ def __init__(self, id=None, score=None, metadata=None, collection_id=None, result_metadata=None, **kwargs): """ Initialize a QueryResult object. :param str id: (optional) The unique identifier of the document. :param float score: (optional) *Deprecated* This field is now part of the **result_metadata** object. :param object metadata: (optional) Metadata of the document. :param str collection_id: (optional) The collection ID of the collection containing the document for this result. :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. :param **kwargs: (optional) Any additional properties. """ self.id = id self.score = score self.metadata = metadata self.collection_id = collection_id self.result_metadata = result_metadata for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a QueryResult object from a json dictionary.""" args = {} xtra = _dict.copy() if 'id' in _dict: args['id'] = _dict.get('id') del xtra['id'] if 'score' in _dict: args['score'] = _dict.get('score') del xtra['score'] if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') del xtra['metadata'] if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') del xtra['collection_id'] if 'result_metadata' in _dict: args['result_metadata'] = QueryResultMetadata._from_dict( _dict.get('result_metadata')) del xtra['result_metadata'] args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: _dict['result_metadata'] = self.result_metadata._to_dict() if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = { 'id', 'score', 'metadata', 'collection_id', 'result_metadata' } if not hasattr(self, '_additionalProperties'): super(QueryResult, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(QueryResult, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this QueryResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryResultMetadata(object): """ Metadata of a query result. :attr float score: An unbounded measure of the relevance of a particular result, dependent on the query and matching document. A higher score indicates a greater match to the query parameters. :attr float confidence: The confidence score for the given result. Calculated based on how relevant the result is estimated to be. confidence can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the result set. """ def __init__(self, score, confidence): """ Initialize a QueryResultMetadata object. :param float score: An unbounded measure of the relevance of a particular result, dependent on the query and matching document. A higher score indicates a greater match to the query parameters. :param float confidence: The confidence score for the given result. Calculated based on how relevant the result is estimated to be. confidence can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the result set. """ self.score = score self.confidence = confidence @classmethod def _from_dict(cls, _dict): """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} if 'score' in _dict: args['score'] = _dict.get('score') else: raise ValueError( 'Required property \'score\' not present in QueryResultMetadata JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: raise ValueError( 'Required property \'confidence\' not present in QueryResultMetadata JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence return _dict def __str__(self): """Return a `str` version of this QueryResultMetadata object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RetrievalDetails(object): """ An object contain retrieval type information. :attr str document_retrieval_strategy: (optional) Indentifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. `continuous_relevancy_training` indicates that the results were returned using the continuous relevancy training model created by result feedback analysis. `untrained` means the results were returned using the standard untrained model. **Note**: In the event of trained collections being queried, but the trained model is not used to return results, the **document_retrieval_strategy** will be listed as `untrained`. """ def __init__(self, document_retrieval_strategy=None): """ Initialize a RetrievalDetails object. :param str document_retrieval_strategy: (optional) Indentifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. `continuous_relevancy_training` indicates that the results were returned using the continuous relevancy training model created by result feedback analysis. `untrained` means the results were returned using the standard untrained model. **Note**: In the event of trained collections being queried, but the trained model is not used to return results, the **document_retrieval_strategy** will be listed as `untrained`. """ self.document_retrieval_strategy = document_retrieval_strategy @classmethod def _from_dict(cls, _dict): """Initialize a RetrievalDetails object from a json dictionary.""" args = {} if 'document_retrieval_strategy' in _dict: args['document_retrieval_strategy'] = _dict.get( 'document_retrieval_strategy') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_retrieval_strategy' ) and self.document_retrieval_strategy is not None: _dict[ 'document_retrieval_strategy'] = self.document_retrieval_strategy return _dict def __str__(self): """Return a `str` version of this RetrievalDetails object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SearchStatus(object): """ Information about the Continuous Relevancy Training for this environment. :attr str scope: (optional) Current scope of the training. Always returned as `environment`. :attr str status: (optional) The current status of Continuous Relevancy Training for this environment. :attr str status_description: (optional) Long description of the current Continuous Relevancy Training status. :attr date last_trained: (optional) The date stamp of the most recent completed training for this environment. """ def __init__(self, scope=None, status=None, status_description=None, last_trained=None): """ Initialize a SearchStatus object. :param str scope: (optional) Current scope of the training. Always returned as `environment`. :param str status: (optional) The current status of Continuous Relevancy Training for this environment. :param str status_description: (optional) Long description of the current Continuous Relevancy Training status. :param date last_trained: (optional) The date stamp of the most recent completed training for this environment. """ self.scope = scope self.status = status self.status_description = status_description self.last_trained = last_trained @classmethod def _from_dict(cls, _dict): """Initialize a SearchStatus object from a json dictionary.""" args = {} if 'scope' in _dict: args['scope'] = _dict.get('scope') if 'status' in _dict: args['status'] = _dict.get('status') if 'status_description' in _dict: args['status_description'] = _dict.get('status_description') if 'last_trained' in _dict: args['last_trained'] = _dict.get('last_trained') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'scope') and self.scope is not None: _dict['scope'] = self.scope if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr( self, 'status_description') and self.status_description is not None: _dict['status_description'] = self.status_description if hasattr(self, 'last_trained') and self.last_trained is not None: _dict['last_trained'] = self.last_trained return _dict def __str__(self): """Return a `str` version of this SearchStatus object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SegmentSettings(object): """ A list of Document Segmentation settings. :attr bool enabled: (optional) Enables/disables the Document Segmentation feature. :attr list[str] selector_tags: (optional) Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. """ def __init__(self, enabled=None, selector_tags=None): """ Initialize a SegmentSettings object. :param bool enabled: (optional) Enables/disables the Document Segmentation feature. :param list[str] selector_tags: (optional) Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. """ self.enabled = enabled self.selector_tags = selector_tags @classmethod def _from_dict(cls, _dict): """Initialize a SegmentSettings object from a json dictionary.""" args = {} if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'selector_tags' in _dict: args['selector_tags'] = _dict.get('selector_tags') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enabled') and self.enabled is not None: _dict['enabled'] = self.enabled if hasattr(self, 'selector_tags') and self.selector_tags is not None: _dict['selector_tags'] = self.selector_tags return _dict def __str__(self): """Return a `str` version of this SegmentSettings object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Source(object): """ Object containing source parameters for the configuration. :attr str type: (optional) The type of source to connect to. - `box` indicates the configuration is to connect an instance of Enterprise Box. - `salesforce` indicates the configuration is to connect to Salesforce. - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint Online. - `web_crawl` indicates the configuration is to perform a web page crawl. :attr str credential_id: (optional) The **credential_id** of the credentials to use to connect to the source. Credentials are defined using the **credentials** method. The **source_type** of the credentials used must match the **type** field specified in this object. :attr SourceSchedule schedule: (optional) Object containing the schedule information for the source. :attr SourceOptions options: (optional) The **options** object defines which items to crawl from the source system. """ def __init__(self, type=None, credential_id=None, schedule=None, options=None): """ Initialize a Source object. :param str type: (optional) The type of source to connect to. - `box` indicates the configuration is to connect an instance of Enterprise Box. - `salesforce` indicates the configuration is to connect to Salesforce. - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint Online. - `web_crawl` indicates the configuration is to perform a web page crawl. :param str credential_id: (optional) The **credential_id** of the credentials to use to connect to the source. Credentials are defined using the **credentials** method. The **source_type** of the credentials used must match the **type** field specified in this object. :param SourceSchedule schedule: (optional) Object containing the schedule information for the source. :param SourceOptions options: (optional) The **options** object defines which items to crawl from the source system. """ self.type = type self.credential_id = credential_id self.schedule = schedule self.options = options @classmethod def _from_dict(cls, _dict): """Initialize a Source object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'schedule' in _dict: args['schedule'] = SourceSchedule._from_dict(_dict.get('schedule')) if 'options' in _dict: args['options'] = SourceOptions._from_dict(_dict.get('options')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'schedule') and self.schedule is not None: _dict['schedule'] = self.schedule._to_dict() if hasattr(self, 'options') and self.options is not None: _dict['options'] = self.options._to_dict() return _dict def __str__(self): """Return a `str` version of this Source object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SourceOptions(object): """ The **options** object defines which items to crawl from the source system. :attr list[SourceOptionsFolder] folders: (optional) Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. :attr list[SourceOptionsObject] objects: (optional) Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the **type** field of the **source** object is set to `salesforce`. :attr list[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. :attr list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. """ def __init__(self, folders=None, objects=None, site_collections=None, urls=None): """ Initialize a SourceOptions object. :param list[SourceOptionsFolder] folders: (optional) Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. :param list[SourceOptionsObject] objects: (optional) Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the **type** field of the **source** object is set to `salesforce`. :param list[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. :param list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. """ self.folders = folders self.objects = objects self.site_collections = site_collections self.urls = urls @classmethod def _from_dict(cls, _dict): """Initialize a SourceOptions object from a json dictionary.""" args = {} if 'folders' in _dict: args['folders'] = [ SourceOptionsFolder._from_dict(x) for x in (_dict.get('folders')) ] if 'objects' in _dict: args['objects'] = [ SourceOptionsObject._from_dict(x) for x in (_dict.get('objects')) ] if 'site_collections' in _dict: args['site_collections'] = [ SourceOptionsSiteColl._from_dict(x) for x in (_dict.get('site_collections')) ] if 'urls' in _dict: args['urls'] = [ SourceOptionsWebCrawl._from_dict(x) for x in (_dict.get('urls')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'folders') and self.folders is not None: _dict['folders'] = [x._to_dict() for x in self.folders] if hasattr(self, 'objects') and self.objects is not None: _dict['objects'] = [x._to_dict() for x in self.objects] if hasattr(self, 'site_collections') and self.site_collections is not None: _dict['site_collections'] = [ x._to_dict() for x in self.site_collections ] if hasattr(self, 'urls') and self.urls is not None: _dict['urls'] = [x._to_dict() for x in self.urls] return _dict def __str__(self): """Return a `str` version of this SourceOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SourceOptionsFolder(object): """ Object that defines a box folder to crawl with this configuration. :attr str owner_user_id: The Box user ID of the user who owns the folder to crawl. :attr str folder_id: The Box folder ID of the folder to crawl. :attr int limit: (optional) The maximum number of documents to crawl for this folder. By default, all documents in the folder are crawled. """ def __init__(self, owner_user_id, folder_id, limit=None): """ Initialize a SourceOptionsFolder object. :param str owner_user_id: The Box user ID of the user who owns the folder to crawl. :param str folder_id: The Box folder ID of the folder to crawl. :param int limit: (optional) The maximum number of documents to crawl for this folder. By default, all documents in the folder are crawled. """ self.owner_user_id = owner_user_id self.folder_id = folder_id self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a SourceOptionsFolder object from a json dictionary.""" args = {} if 'owner_user_id' in _dict: args['owner_user_id'] = _dict.get('owner_user_id') else: raise ValueError( 'Required property \'owner_user_id\' not present in SourceOptionsFolder JSON' ) if 'folder_id' in _dict: args['folder_id'] = _dict.get('folder_id') else: raise ValueError( 'Required property \'folder_id\' not present in SourceOptionsFolder JSON' ) if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'owner_user_id') and self.owner_user_id is not None: _dict['owner_user_id'] = self.owner_user_id if hasattr(self, 'folder_id') and self.folder_id is not None: _dict['folder_id'] = self.folder_id if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this SourceOptionsFolder object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SourceOptionsObject(object): """ Object that defines a Salesforce document object type crawl with this configuration. :attr str name: The name of the Salesforce document object to crawl. For example, `case`. :attr int limit: (optional) The maximum number of documents to crawl for this document object. By default, all documents in the document object are crawled. """ def __init__(self, name, limit=None): """ Initialize a SourceOptionsObject object. :param str name: The name of the Salesforce document object to crawl. For example, `case`. :param int limit: (optional) The maximum number of documents to crawl for this document object. By default, all documents in the document object are crawled. """ self.name = name self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a SourceOptionsObject object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in SourceOptionsObject JSON' ) if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this SourceOptionsObject object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SourceOptionsSiteColl(object): """ Object that defines a Microsoft SharePoint site collection to crawl with this configuration. :attr str site_collection_path: The Microsoft SharePoint Online site collection path to crawl. The path must be be relative to the **organization_url** that was specified in the credentials associated with this source configuration. :attr int limit: (optional) The maximum number of documents to crawl for this site collection. By default, all documents in the site collection are crawled. """ def __init__(self, site_collection_path, limit=None): """ Initialize a SourceOptionsSiteColl object. :param str site_collection_path: The Microsoft SharePoint Online site collection path to crawl. The path must be be relative to the **organization_url** that was specified in the credentials associated with this source configuration. :param int limit: (optional) The maximum number of documents to crawl for this site collection. By default, all documents in the site collection are crawled. """ self.site_collection_path = site_collection_path self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a SourceOptionsSiteColl object from a json dictionary.""" args = {} if 'site_collection_path' in _dict: args['site_collection_path'] = _dict.get('site_collection_path') else: raise ValueError( 'Required property \'site_collection_path\' not present in SourceOptionsSiteColl JSON' ) if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'site_collection_path' ) and self.site_collection_path is not None: _dict['site_collection_path'] = self.site_collection_path if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this SourceOptionsSiteColl object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SourceOptionsWebCrawl(object): """ Object defining which URL to crawl and how to crawl it. :attr str url: The starting URL to crawl. :attr bool limit_to_starting_hosts: (optional) When `true`, crawls of the specified URL are limited to the host part of the **url** field. :attr str crawl_speed: (optional) The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with a delay between each call. `normal` means as many as two URLs are fectched concurrently with a short delay between fetch calls. `aggressive` means that up to ten URLs are fetched concurrently with a short delay between fetch calls. :attr bool allow_untrusted_certificate: (optional) When `true`, allows the crawl to interact with HTTPS sites with SSL certificates with untrusted signers. :attr int maximum_hops: (optional) The maximum number of hops to make from the initial URL. When a page is crawled each link on that page will also be crawled if it is within the **maximum_hops** from the initial URL. The first page crawled is 0 hops, each link crawled from the first page is 1 hop, each link crawled from those pages is 2 hops, and so on. :attr int request_timeout: (optional) The maximum milliseconds to wait for a response from the web server. :attr bool override_robots_txt: (optional) When `true`, the crawler will ignore any `robots.txt` encountered by the crawler. This should only ever be done when crawling a web site the user owns. This must be be set to `true` when a **gateway_id** is specied in the **credentials**. """ def __init__(self, url, limit_to_starting_hosts=None, crawl_speed=None, allow_untrusted_certificate=None, maximum_hops=None, request_timeout=None, override_robots_txt=None): """ Initialize a SourceOptionsWebCrawl object. :param str url: The starting URL to crawl. :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the specified URL are limited to the host part of the **url** field. :param str crawl_speed: (optional) The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with a delay between each call. `normal` means as many as two URLs are fectched concurrently with a short delay between fetch calls. `aggressive` means that up to ten URLs are fetched concurrently with a short delay between fetch calls. :param bool allow_untrusted_certificate: (optional) When `true`, allows the crawl to interact with HTTPS sites with SSL certificates with untrusted signers. :param int maximum_hops: (optional) The maximum number of hops to make from the initial URL. When a page is crawled each link on that page will also be crawled if it is within the **maximum_hops** from the initial URL. The first page crawled is 0 hops, each link crawled from the first page is 1 hop, each link crawled from those pages is 2 hops, and so on. :param int request_timeout: (optional) The maximum milliseconds to wait for a response from the web server. :param bool override_robots_txt: (optional) When `true`, the crawler will ignore any `robots.txt` encountered by the crawler. This should only ever be done when crawling a web site the user owns. This must be be set to `true` when a **gateway_id** is specied in the **credentials**. """ self.url = url self.limit_to_starting_hosts = limit_to_starting_hosts self.crawl_speed = crawl_speed self.allow_untrusted_certificate = allow_untrusted_certificate self.maximum_hops = maximum_hops self.request_timeout = request_timeout self.override_robots_txt = override_robots_txt @classmethod def _from_dict(cls, _dict): """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" args = {} if 'url' in _dict: args['url'] = _dict.get('url') else: raise ValueError( 'Required property \'url\' not present in SourceOptionsWebCrawl JSON' ) if 'limit_to_starting_hosts' in _dict: args['limit_to_starting_hosts'] = _dict.get( 'limit_to_starting_hosts') if 'crawl_speed' in _dict: args['crawl_speed'] = _dict.get('crawl_speed') if 'allow_untrusted_certificate' in _dict: args['allow_untrusted_certificate'] = _dict.get( 'allow_untrusted_certificate') if 'maximum_hops' in _dict: args['maximum_hops'] = _dict.get('maximum_hops') if 'request_timeout' in _dict: args['request_timeout'] = _dict.get('request_timeout') if 'override_robots_txt' in _dict: args['override_robots_txt'] = _dict.get('override_robots_txt') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'limit_to_starting_hosts' ) and self.limit_to_starting_hosts is not None: _dict['limit_to_starting_hosts'] = self.limit_to_starting_hosts if hasattr(self, 'crawl_speed') and self.crawl_speed is not None: _dict['crawl_speed'] = self.crawl_speed if hasattr(self, 'allow_untrusted_certificate' ) and self.allow_untrusted_certificate is not None: _dict[ 'allow_untrusted_certificate'] = self.allow_untrusted_certificate if hasattr(self, 'maximum_hops') and self.maximum_hops is not None: _dict['maximum_hops'] = self.maximum_hops if hasattr(self, 'request_timeout') and self.request_timeout is not None: _dict['request_timeout'] = self.request_timeout if hasattr( self, 'override_robots_txt') and self.override_robots_txt is not None: _dict['override_robots_txt'] = self.override_robots_txt return _dict def __str__(self): """Return a `str` version of this SourceOptionsWebCrawl object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SourceSchedule(object): """ Object containing the schedule information for the source. :attr bool enabled: (optional) When `true`, the source is re-crawled based on the **frequency** field in this object. When `false` the source is not re-crawled; When `false` and connecting to Salesforce the source is crawled annually. :attr str time_zone: (optional) The time zone to base source crawl times on. Possible values correspond to the IANA (Internet Assigned Numbers Authority) time zones list. :attr str frequency: (optional) The crawl schedule in the specified **time_zone**. - `daily`: Runs every day between 00:00 and 06:00. - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. """ def __init__(self, enabled=None, time_zone=None, frequency=None): """ Initialize a SourceSchedule object. :param bool enabled: (optional) When `true`, the source is re-crawled based on the **frequency** field in this object. When `false` the source is not re-crawled; When `false` and connecting to Salesforce the source is crawled annually. :param str time_zone: (optional) The time zone to base source crawl times on. Possible values correspond to the IANA (Internet Assigned Numbers Authority) time zones list. :param str frequency: (optional) The crawl schedule in the specified **time_zone**. - `daily`: Runs every day between 00:00 and 06:00. - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. """ self.enabled = enabled self.time_zone = time_zone self.frequency = frequency @classmethod def _from_dict(cls, _dict): """Initialize a SourceSchedule object from a json dictionary.""" args = {} if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'time_zone' in _dict: args['time_zone'] = _dict.get('time_zone') if 'frequency' in _dict: args['frequency'] = _dict.get('frequency') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enabled') and self.enabled is not None: _dict['enabled'] = self.enabled if hasattr(self, 'time_zone') and self.time_zone is not None: _dict['time_zone'] = self.time_zone if hasattr(self, 'frequency') and self.frequency is not None: _dict['frequency'] = self.frequency return _dict def __str__(self): """Return a `str` version of this SourceSchedule object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SourceStatus(object): """ Object containing source crawl status information. :attr str status: (optional) The current status of the source crawl for this collection. This field returns `not_configured` if the default configuration for this source does not have a **source** object defined. - `running` indicates that a crawl to fetch more documents is in progress. - `complete` indicates that the crawl has completed with no errors. - `complete_with_notices` indicates that some notices were generated during the crawl. Notices can be checked by using the **notices** query method. - `stopped` indicates that the crawl has stopped but is not complete. :attr datetime last_updated: (optional) Date in UTC format indicating when the last crawl was attempted. If `null`, no crawl was completed. """ def __init__(self, status=None, last_updated=None): """ Initialize a SourceStatus object. :param str status: (optional) The current status of the source crawl for this collection. This field returns `not_configured` if the default configuration for this source does not have a **source** object defined. - `running` indicates that a crawl to fetch more documents is in progress. - `complete` indicates that the crawl has completed with no errors. - `complete_with_notices` indicates that some notices were generated during the crawl. Notices can be checked by using the **notices** query method. - `stopped` indicates that the crawl has stopped but is not complete. :param datetime last_updated: (optional) Date in UTC format indicating when the last crawl was attempted. If `null`, no crawl was completed. """ self.status = status self.last_updated = last_updated @classmethod def _from_dict(cls, _dict): """Initialize a SourceStatus object from a json dictionary.""" args = {} if 'status' in _dict: args['status'] = _dict.get('status') if 'last_updated' in _dict: args['last_updated'] = string_to_datetime(_dict.get('last_updated')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'last_updated') and self.last_updated is not None: _dict['last_updated'] = datetime_to_string(self.last_updated) return _dict def __str__(self): """Return a `str` version of this SourceStatus object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TestDocument(object): """ TestDocument. :attr str configuration_id: (optional) The unique identifier for the configuration. :attr str status: (optional) Status of the preview operation. :attr int enriched_field_units: (optional) The number of 10-kB chunks of field data that were enriched. This can be used to estimate the cost of running a real ingestion. :attr str original_media_type: (optional) Format of the test document. :attr list[DocumentSnapshot] snapshots: (optional) An array of objects that describe each step in the preview process. :attr list[Notice] notices: (optional) An array of notice messages about the preview operation. """ def __init__(self, configuration_id=None, status=None, enriched_field_units=None, original_media_type=None, snapshots=None, notices=None): """ Initialize a TestDocument object. :param str configuration_id: (optional) The unique identifier for the configuration. :param str status: (optional) Status of the preview operation. :param int enriched_field_units: (optional) The number of 10-kB chunks of field data that were enriched. This can be used to estimate the cost of running a real ingestion. :param str original_media_type: (optional) Format of the test document. :param list[DocumentSnapshot] snapshots: (optional) An array of objects that describe each step in the preview process. :param list[Notice] notices: (optional) An array of notice messages about the preview operation. """ self.configuration_id = configuration_id self.status = status self.enriched_field_units = enriched_field_units self.original_media_type = original_media_type self.snapshots = snapshots self.notices = notices @classmethod def _from_dict(cls, _dict): """Initialize a TestDocument object from a json dictionary.""" args = {} if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') if 'status' in _dict: args['status'] = _dict.get('status') if 'enriched_field_units' in _dict: args['enriched_field_units'] = _dict.get('enriched_field_units') if 'original_media_type' in _dict: args['original_media_type'] = _dict.get('original_media_type') if 'snapshots' in _dict: args['snapshots'] = [ DocumentSnapshot._from_dict(x) for x in (_dict.get('snapshots')) ] if 'notices' in _dict: args['notices'] = [ Notice._from_dict(x) for x in (_dict.get('notices')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configuration_id') and self.configuration_id is not None: _dict['configuration_id'] = self.configuration_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'enriched_field_units' ) and self.enriched_field_units is not None: _dict['enriched_field_units'] = self.enriched_field_units if hasattr( self, 'original_media_type') and self.original_media_type is not None: _dict['original_media_type'] = self.original_media_type if hasattr(self, 'snapshots') and self.snapshots is not None: _dict['snapshots'] = [x._to_dict() for x in self.snapshots] if hasattr(self, 'notices') and self.notices is not None: _dict['notices'] = [x._to_dict() for x in self.notices] return _dict def __str__(self): """Return a `str` version of this TestDocument object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TokenDictRule(object): """ An object defining a single tokenizaion rule. :attr str text: The string to tokenize. :attr list[str] tokens: Array of tokens that the `text` field is split into when found. :attr list[str] readings: (optional) Array of tokens that represent the content of the `text` field in an alternate character set. :attr str part_of_speech: The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. """ def __init__(self, text, tokens, part_of_speech, readings=None): """ Initialize a TokenDictRule object. :param str text: The string to tokenize. :param list[str] tokens: Array of tokens that the `text` field is split into when found. :param str part_of_speech: The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. :param list[str] readings: (optional) Array of tokens that represent the content of the `text` field in an alternate character set. """ self.text = text self.tokens = tokens self.readings = readings self.part_of_speech = part_of_speech @classmethod def _from_dict(cls, _dict): """Initialize a TokenDictRule object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in TokenDictRule JSON') if 'tokens' in _dict: args['tokens'] = _dict.get('tokens') else: raise ValueError( 'Required property \'tokens\' not present in TokenDictRule JSON' ) if 'readings' in _dict: args['readings'] = _dict.get('readings') if 'part_of_speech' in _dict: args['part_of_speech'] = _dict.get('part_of_speech') else: raise ValueError( 'Required property \'part_of_speech\' not present in TokenDictRule JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'tokens') and self.tokens is not None: _dict['tokens'] = self.tokens if hasattr(self, 'readings') and self.readings is not None: _dict['readings'] = self.readings if hasattr(self, 'part_of_speech') and self.part_of_speech is not None: _dict['part_of_speech'] = self.part_of_speech return _dict def __str__(self): """Return a `str` version of this TokenDictRule object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TokenDictStatusResponse(object): """ Object describing the current status of the wordlist. :attr str status: (optional) Current wordlist status for the specified collection. :attr str type: (optional) The type for this wordlist. Can be `tokenization_dictionary` or `stopwords`. """ def __init__(self, status=None, type=None): """ Initialize a TokenDictStatusResponse object. :param str status: (optional) Current wordlist status for the specified collection. :param str type: (optional) The type for this wordlist. Can be `tokenization_dictionary` or `stopwords`. """ self.status = status self.type = type @classmethod def _from_dict(cls, _dict): """Initialize a TokenDictStatusResponse object from a json dictionary.""" args = {} if 'status' in _dict: args['status'] = _dict.get('status') if 'type' in _dict: args['type'] = _dict.get('type') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type return _dict def __str__(self): """Return a `str` version of this TokenDictStatusResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TopHitsResults(object): """ TopHitsResults. :attr int matching_results: (optional) Number of matching results. :attr list[QueryResult] hits: (optional) Top results returned by the aggregation. """ def __init__(self, matching_results=None, hits=None): """ Initialize a TopHitsResults object. :param int matching_results: (optional) Number of matching results. :param list[QueryResult] hits: (optional) Top results returned by the aggregation. """ self.matching_results = matching_results self.hits = hits @classmethod def _from_dict(cls, _dict): """Initialize a TopHitsResults object from a json dictionary.""" args = {} if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'hits' in _dict: args['hits'] = [ QueryResult._from_dict(x) for x in (_dict.get('hits')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'hits') and self.hits is not None: _dict['hits'] = [x._to_dict() for x in self.hits] return _dict def __str__(self): """Return a `str` version of this TopHitsResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TrainingDataSet(object): """ TrainingDataSet. :attr str environment_id: (optional) :attr str collection_id: (optional) :attr list[TrainingQuery] queries: (optional) """ def __init__(self, environment_id=None, collection_id=None, queries=None): """ Initialize a TrainingDataSet object. :param str environment_id: (optional) :param str collection_id: (optional) :param list[TrainingQuery] queries: (optional) """ self.environment_id = environment_id self.collection_id = collection_id self.queries = queries @classmethod def _from_dict(cls, _dict): """Initialize a TrainingDataSet object from a json dictionary.""" args = {} if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'queries' in _dict: args['queries'] = [ TrainingQuery._from_dict(x) for x in (_dict.get('queries')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environment_id') and self.environment_id is not None: _dict['environment_id'] = self.environment_id if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'queries') and self.queries is not None: _dict['queries'] = [x._to_dict() for x in self.queries] return _dict def __str__(self): """Return a `str` version of this TrainingDataSet object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TrainingExample(object): """ TrainingExample. :attr str document_id: (optional) :attr str cross_reference: (optional) :attr int relevance: (optional) """ def __init__(self, document_id=None, cross_reference=None, relevance=None): """ Initialize a TrainingExample object. :param str document_id: (optional) :param str cross_reference: (optional) :param int relevance: (optional) """ self.document_id = document_id self.cross_reference = cross_reference self.relevance = relevance @classmethod def _from_dict(cls, _dict): """Initialize a TrainingExample object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'cross_reference' in _dict: args['cross_reference'] = _dict.get('cross_reference') if 'relevance' in _dict: args['relevance'] = _dict.get('relevance') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id if hasattr(self, 'cross_reference') and self.cross_reference is not None: _dict['cross_reference'] = self.cross_reference if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevance return _dict def __str__(self): """Return a `str` version of this TrainingExample object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TrainingExampleList(object): """ TrainingExampleList. :attr list[TrainingExample] examples: (optional) """ def __init__(self, examples=None): """ Initialize a TrainingExampleList object. :param list[TrainingExample] examples: (optional) """ self.examples = examples @classmethod def _from_dict(cls, _dict): """Initialize a TrainingExampleList object from a json dictionary.""" args = {} if 'examples' in _dict: args['examples'] = [ TrainingExample._from_dict(x) for x in (_dict.get('examples')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict def __str__(self): """Return a `str` version of this TrainingExampleList object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TrainingQuery(object): """ TrainingQuery. :attr str query_id: (optional) :attr str natural_language_query: (optional) :attr str filter: (optional) :attr list[TrainingExample] examples: (optional) """ def __init__(self, query_id=None, natural_language_query=None, filter=None, examples=None): """ Initialize a TrainingQuery object. :param str query_id: (optional) :param str natural_language_query: (optional) :param str filter: (optional) :param list[TrainingExample] examples: (optional) """ self.query_id = query_id self.natural_language_query = natural_language_query self.filter = filter self.examples = examples @classmethod def _from_dict(cls, _dict): """Initialize a TrainingQuery object from a json dictionary.""" args = {} if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') if 'natural_language_query' in _dict: args['natural_language_query'] = _dict.get('natural_language_query') if 'filter' in _dict: args['filter'] = _dict.get('filter') if 'examples' in _dict: args['examples'] = [ TrainingExample._from_dict(x) for x in (_dict.get('examples')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'query_id') and self.query_id is not None: _dict['query_id'] = self.query_id if hasattr(self, 'natural_language_query' ) and self.natural_language_query is not None: _dict['natural_language_query'] = self.natural_language_query if hasattr(self, 'filter') and self.filter is not None: _dict['filter'] = self.filter if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict def __str__(self): """Return a `str` version of this TrainingQuery object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TrainingStatus(object): """ TrainingStatus. :attr int total_examples: (optional) :attr bool available: (optional) :attr bool processing: (optional) :attr bool minimum_queries_added: (optional) :attr bool minimum_examples_added: (optional) :attr bool sufficient_label_diversity: (optional) :attr int notices: (optional) :attr datetime successfully_trained: (optional) :attr datetime data_updated: (optional) """ def __init__(self, total_examples=None, available=None, processing=None, minimum_queries_added=None, minimum_examples_added=None, sufficient_label_diversity=None, notices=None, successfully_trained=None, data_updated=None): """ Initialize a TrainingStatus object. :param int total_examples: (optional) :param bool available: (optional) :param bool processing: (optional) :param bool minimum_queries_added: (optional) :param bool minimum_examples_added: (optional) :param bool sufficient_label_diversity: (optional) :param int notices: (optional) :param datetime successfully_trained: (optional) :param datetime data_updated: (optional) """ self.total_examples = total_examples self.available = available self.processing = processing self.minimum_queries_added = minimum_queries_added self.minimum_examples_added = minimum_examples_added self.sufficient_label_diversity = sufficient_label_diversity self.notices = notices self.successfully_trained = successfully_trained self.data_updated = data_updated @classmethod def _from_dict(cls, _dict): """Initialize a TrainingStatus object from a json dictionary.""" args = {} if 'total_examples' in _dict: args['total_examples'] = _dict.get('total_examples') if 'available' in _dict: args['available'] = _dict.get('available') if 'processing' in _dict: args['processing'] = _dict.get('processing') if 'minimum_queries_added' in _dict: args['minimum_queries_added'] = _dict.get('minimum_queries_added') if 'minimum_examples_added' in _dict: args['minimum_examples_added'] = _dict.get('minimum_examples_added') if 'sufficient_label_diversity' in _dict: args['sufficient_label_diversity'] = _dict.get( 'sufficient_label_diversity') if 'notices' in _dict: args['notices'] = _dict.get('notices') if 'successfully_trained' in _dict: args['successfully_trained'] = string_to_datetime( _dict.get('successfully_trained')) if 'data_updated' in _dict: args['data_updated'] = string_to_datetime(_dict.get('data_updated')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'total_examples') and self.total_examples is not None: _dict['total_examples'] = self.total_examples if hasattr(self, 'available') and self.available is not None: _dict['available'] = self.available if hasattr(self, 'processing') and self.processing is not None: _dict['processing'] = self.processing if hasattr(self, 'minimum_queries_added' ) and self.minimum_queries_added is not None: _dict['minimum_queries_added'] = self.minimum_queries_added if hasattr(self, 'minimum_examples_added' ) and self.minimum_examples_added is not None: _dict['minimum_examples_added'] = self.minimum_examples_added if hasattr(self, 'sufficient_label_diversity' ) and self.sufficient_label_diversity is not None: _dict[ 'sufficient_label_diversity'] = self.sufficient_label_diversity if hasattr(self, 'notices') and self.notices is not None: _dict['notices'] = self.notices if hasattr(self, 'successfully_trained' ) and self.successfully_trained is not None: _dict['successfully_trained'] = datetime_to_string( self.successfully_trained) if hasattr(self, 'data_updated') and self.data_updated is not None: _dict['data_updated'] = datetime_to_string(self.data_updated) return _dict def __str__(self): """Return a `str` version of this TrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WordHeadingDetection(object): """ WordHeadingDetection. :attr list[FontSetting] fonts: (optional) :attr list[WordStyle] styles: (optional) """ def __init__(self, fonts=None, styles=None): """ Initialize a WordHeadingDetection object. :param list[FontSetting] fonts: (optional) :param list[WordStyle] styles: (optional) """ self.fonts = fonts self.styles = styles @classmethod def _from_dict(cls, _dict): """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} if 'fonts' in _dict: args['fonts'] = [ FontSetting._from_dict(x) for x in (_dict.get('fonts')) ] if 'styles' in _dict: args['styles'] = [ WordStyle._from_dict(x) for x in (_dict.get('styles')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: _dict['fonts'] = [x._to_dict() for x in self.fonts] if hasattr(self, 'styles') and self.styles is not None: _dict['styles'] = [x._to_dict() for x in self.styles] return _dict def __str__(self): """Return a `str` version of this WordHeadingDetection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WordSettings(object): """ A list of Word conversion settings. :attr WordHeadingDetection heading: (optional) """ def __init__(self, heading=None): """ Initialize a WordSettings object. :param WordHeadingDetection heading: (optional) """ self.heading = heading @classmethod def _from_dict(cls, _dict): """Initialize a WordSettings object from a json dictionary.""" args = {} if 'heading' in _dict: args['heading'] = WordHeadingDetection._from_dict( _dict.get('heading')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: _dict['heading'] = self.heading._to_dict() return _dict def __str__(self): """Return a `str` version of this WordSettings object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WordStyle(object): """ WordStyle. :attr int level: (optional) :attr list[str] names: (optional) """ def __init__(self, level=None, names=None): """ Initialize a WordStyle object. :param int level: (optional) :param list[str] names: (optional) """ self.level = level self.names = names @classmethod def _from_dict(cls, _dict): """Initialize a WordStyle object from a json dictionary.""" args = {} if 'level' in _dict: args['level'] = _dict.get('level') if 'names' in _dict: args['names'] = _dict.get('names') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'level') and self.level is not None: _dict['level'] = self.level if hasattr(self, 'names') and self.names is not None: _dict['names'] = self.names return _dict def __str__(self): """Return a `str` version of this WordStyle object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class XPathPatterns(object): """ XPathPatterns. :attr list[str] xpaths: (optional) """ def __init__(self, xpaths=None): """ Initialize a XPathPatterns object. :param list[str] xpaths: (optional) """ self.xpaths = xpaths @classmethod def _from_dict(cls, _dict): """Initialize a XPathPatterns object from a json dictionary.""" args = {} if 'xpaths' in _dict: args['xpaths'] = _dict.get('xpaths') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'xpaths') and self.xpaths is not None: _dict['xpaths'] = self.xpaths return _dict def __str__(self): """Return a `str` version of this XPathPatterns object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Calculation(object): """ Calculation. :attr str field: (optional) The field where the aggregation is located in the document. :attr float value: (optional) Value of the aggregation. """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None, field=None, value=None): """ Initialize a Calculation object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. :param str field: (optional) The field where the aggregation is located in the document. :param float value: (optional) Value of the aggregation. """ self.field = field self.value = value @classmethod def _from_dict(cls, _dict): """Initialize a Calculation object from a json dictionary.""" args = {} if 'field' in _dict: args['field'] = _dict.get('field') if 'value' in _dict: args['value'] = _dict.get('value') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value return _dict def __str__(self): """Return a `str` version of this Calculation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Filter(object): """ Filter. :attr str match: (optional) The match the aggregated results queried for. """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None, match=None): """ Initialize a Filter object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. :param str match: (optional) The match the aggregated results queried for. """ self.match = match @classmethod def _from_dict(cls, _dict): """Initialize a Filter object from a json dictionary.""" args = {} if 'match' in _dict: args['match'] = _dict.get('match') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'match') and self.match is not None: _dict['match'] = self.match return _dict def __str__(self): """Return a `str` version of this Filter object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Histogram(object): """ Histogram. :attr str field: (optional) The field where the aggregation is located in the document. :attr int interval: (optional) Interval of the aggregation. (For 'histogram' type). """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None, field=None, interval=None): """ Initialize a Histogram object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. :param str field: (optional) The field where the aggregation is located in the document. :param int interval: (optional) Interval of the aggregation. (For 'histogram' type). """ self.field = field self.interval = interval @classmethod def _from_dict(cls, _dict): """Initialize a Histogram object from a json dictionary.""" args = {} if 'field' in _dict: args['field'] = _dict.get('field') if 'interval' in _dict: args['interval'] = _dict.get('interval') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: _dict['interval'] = self.interval return _dict def __str__(self): """Return a `str` version of this Histogram object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Nested(object): """ Nested. :attr str path: (optional) The area of the results the aggregation was restricted to. """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None, path=None): """ Initialize a Nested object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. :param str path: (optional) The area of the results the aggregation was restricted to. """ self.path = path @classmethod def _from_dict(cls, _dict): """Initialize a Nested object from a json dictionary.""" args = {} if 'path' in _dict: args['path'] = _dict.get('path') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'path') and self.path is not None: _dict['path'] = self.path return _dict def __str__(self): """Return a `str` version of this Nested object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Term(object): """ Term. :attr str field: (optional) The field where the aggregation is located in the document. :attr int count: (optional) """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None, field=None, count=None): """ Initialize a Term object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. :param str field: (optional) The field where the aggregation is located in the document. :param int count: (optional) """ self.field = field self.count = count @classmethod def _from_dict(cls, _dict): """Initialize a Term object from a json dictionary.""" args = {} if 'field' in _dict: args['field'] = _dict.get('field') if 'count' in _dict: args['count'] = _dict.get('count') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count return _dict def __str__(self): """Return a `str` version of this Term object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Timeslice(object): """ Timeslice. :attr str field: (optional) The field where the aggregation is located in the document. :attr str interval: (optional) Interval of the aggregation. Valid date interval values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, month/months, and year/years. :attr bool anomaly: (optional) Used to indicate that anomaly detection should be performed. Anomaly detection is used to locate unusual datapoints within a time series. """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None, field=None, interval=None, anomaly=None): """ Initialize a Timeslice object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. :param str field: (optional) The field where the aggregation is located in the document. :param str interval: (optional) Interval of the aggregation. Valid date interval values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, month/months, and year/years. :param bool anomaly: (optional) Used to indicate that anomaly detection should be performed. Anomaly detection is used to locate unusual datapoints within a time series. """ self.field = field self.interval = interval self.anomaly = anomaly @classmethod def _from_dict(cls, _dict): """Initialize a Timeslice object from a json dictionary.""" args = {} if 'field' in _dict: args['field'] = _dict.get('field') if 'interval' in _dict: args['interval'] = _dict.get('interval') if 'anomaly' in _dict: args['anomaly'] = _dict.get('anomaly') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: _dict['interval'] = self.interval if hasattr(self, 'anomaly') and self.anomaly is not None: _dict['anomaly'] = self.anomaly return _dict def __str__(self): """Return a `str` version of this Timeslice object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TopHits(object): """ TopHits. :attr int size: (optional) Number of top hits returned by the aggregation. :attr TopHitsResults hits: (optional) """ def __init__(self, type=None, results=None, matching_results=None, aggregations=None, size=None, hits=None): """ Initialize a TopHits object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. :param list[AggregationResult] results: (optional) :param int matching_results: (optional) Number of matching results. :param list[QueryAggregation] aggregations: (optional) Aggregations returned by the Discovery service. :param int size: (optional) Number of top hits returned by the aggregation. :param TopHitsResults hits: (optional) """ self.size = size self.hits = hits @classmethod def _from_dict(cls, _dict): """Initialize a TopHits object from a json dictionary.""" args = {} if 'size' in _dict: args['size'] = _dict.get('size') if 'hits' in _dict: args['hits'] = TopHitsResults._from_dict(_dict.get('hits')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'size') and self.size is not None: _dict['size'] = self.size if hasattr(self, 'hits') and self.hits is not None: _dict['hits'] = self.hits._to_dict() return _dict def __str__(self): """Return a `str` version of this TopHits object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/compare_comply_v1.py0000644000076500000240000057110513451412155030412 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ IBM Watson™ Compare and Comply analyzes governing documents to provide details about critical aspects of the documents. """ from __future__ import absolute_import import json from .watson_service import datetime_to_string, string_to_datetime from os.path import basename from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class CompareComplyV1(WatsonService): """The Compare Comply V1 service.""" default_url = 'https://gateway.watsonplatform.net/compare-comply/api' def __init__( self, version, url=default_url, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Compare Comply service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/compare-comply/api"). The base url may differ between Bluemix regions. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='compare-comply', url=url, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Compare Comply') self.version = version ######################### # HTML conversion ######################### def convert_to_html(self, file, model_id=None, file_content_type=None, filename=None, **kwargs): """ Convert file to HTML. Convert an uploaded file to HTML. :param file file: The file to convert. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param str file_content_type: The content type of file. :param str filename: The filename for file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if file is None: raise ValueError('file must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=convert_to_html' params = {'version': self.version, 'model_id': model_id} form_data = {} if not filename and hasattr(file, 'name'): filename = basename(file.name) if not filename: raise ValueError('filename must be provided') form_data['file'] = (filename, file, file_content_type or 'application/octet-stream') url = '/v1/html_conversion' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Element classification ######################### def classify_elements(self, file, model_id=None, file_content_type=None, filename=None, **kwargs): """ Classify the elements of a document. Analyze an uploaded file's structural and semantic elements. :param file file: The file to classify. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param str file_content_type: The content type of file. :param str filename: The filename for file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if file is None: raise ValueError('file must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=classify_elements' params = {'version': self.version, 'model_id': model_id} form_data = {} if not filename and hasattr(file, 'name'): filename = basename(file.name) form_data['file'] = (filename, file, file_content_type or 'application/octet-stream') url = '/v1/element_classification' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Tables ######################### def extract_tables(self, file, model_id=None, file_content_type=None, filename=None, **kwargs): """ Extract a document's tables. Extract and analyze an uploaded file's tables. :param file file: The file on which to run table extraction. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param str file_content_type: The content type of file. :param str filename: The filename for file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if file is None: raise ValueError('file must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=extract_tables' params = {'version': self.version, 'model_id': model_id} form_data = {} if not filename and hasattr(file, 'name'): filename = basename(file.name) form_data['file'] = (filename, file, file_content_type or 'application/octet-stream') url = '/v1/tables' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Comparison ######################### def compare_documents(self, file_1, file_2, file_1_label=None, file_2_label=None, model_id=None, file_1_content_type=None, file_1_filename=None, file_2_content_type=None, file_2_filename=None, **kwargs): """ Compare two documents. Compare two uploaded input files. Uploaded files must be in the same file format. :param file file_1: The first file to compare. :param file file_2: The second file to compare. :param str file_1_label: A text label for the first file. :param str file_2_label: A text label for the second file. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param str file_1_content_type: The content type of file_1. :param str file_1_filename: The filename for file_1. :param str file_2_content_type: The content type of file_2. :param str file_2_filename: The filename for file_2. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if file_1 is None: raise ValueError('file_1 must be provided') if file_2 is None: raise ValueError('file_2 must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=compare_documents' params = { 'version': self.version, 'file_1_label': file_1_label, 'file_2_label': file_2_label, 'model_id': model_id } form_data = {} if not file_1_filename and hasattr(file_1, 'name'): file_1_filename = basename(file_1.name) form_data['file_1'] = (file_1_filename, file_1, file_1_content_type or 'application/octet-stream') if not file_2_filename and hasattr(file_2, 'name'): file_2_filename = basename(file_2.name) form_data['file_2'] = (file_2_filename, file_2, file_2_content_type or 'application/octet-stream') url = '/v1/comparison' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response ######################### # Feedback ######################### def add_feedback(self, feedback_data, user_id=None, comment=None, **kwargs): """ Add feedback. Adds feedback in the form of _labels_ from a subject-matter expert (SME) to a governing document. **Important:** Feedback is not immediately incorporated into the training model, nor is it guaranteed to be incorporated at a later date. Instead, submitted feedback is used to suggest future updates to the training model. :param FeedbackDataInput feedback_data: Feedback data for submission. :param str user_id: An optional string identifying the user. :param str comment: An optional comment on or description of the feedback. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if feedback_data is None: raise ValueError('feedback_data must be provided') feedback_data = self._convert_model(feedback_data, FeedbackDataInput) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=add_feedback' params = {'version': self.version} data = { 'feedback_data': feedback_data, 'user_id': user_id, 'comment': comment } url = '/v1/feedback' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_feedback(self, feedback_id, model_id=None, **kwargs): """ Deletes a specified feedback entry. :param str feedback_id: A string that specifies the feedback entry to be deleted from the document. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if feedback_id is None: raise ValueError('feedback_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=delete_feedback' params = {'version': self.version, 'model_id': model_id} url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_feedback(self, feedback_id, model_id=None, **kwargs): """ List a specified feedback entry. :param str feedback_id: A string that specifies the feedback entry to be included in the output. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if feedback_id is None: raise ValueError('feedback_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=get_feedback' params = {'version': self.version, 'model_id': model_id} url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_feedback(self, feedback_type=None, before=None, after=None, document_title=None, model_id=None, model_version=None, category_removed=None, category_added=None, category_not_changed=None, type_removed=None, type_added=None, type_not_changed=None, page_limit=None, cursor=None, sort=None, include_total=None, **kwargs): """ List the feedback in documents. :param str feedback_type: An optional string that filters the output to include only feedback with the specified feedback type. The only permitted value is `element_classification`. :param date before: An optional string in the format `YYYY-MM-DD` that filters the output to include only feedback that was added before the specified date. :param date after: An optional string in the format `YYYY-MM-DD` that filters the output to include only feedback that was added after the specified date. :param str document_title: An optional string that filters the output to include only feedback from the document with the specified `document_title`. :param str model_id: An optional string that filters the output to include only feedback with the specified `model_id`. The only permitted value is `contracts`. :param str model_version: An optional string that filters the output to include only feedback with the specified `model_version`. :param str category_removed: An optional string in the form of a comma-separated list of categories. If this is specified, the service filters the output to include only feedback that has at least one category from the list removed. :param str category_added: An optional string in the form of a comma-separated list of categories. If this is specified, the service filters the output to include only feedback that has at least one category from the list added. :param str category_not_changed: An optional string in the form of a comma-separated list of categories. If this is specified, the service filters the output to include only feedback that has at least one category from the list unchanged. :param str type_removed: An optional string of comma-separated `nature`:`party` pairs. If this is specified, the service filters the output to include only feedback that has at least one `nature`:`party` pair from the list removed. :param str type_added: An optional string of comma-separated `nature`:`party` pairs. If this is specified, the service filters the output to include only feedback that has at least one `nature`:`party` pair from the list removed. :param str type_not_changed: An optional string of comma-separated `nature`:`party` pairs. If this is specified, the service filters the output to include only feedback that has at least one `nature`:`party` pair from the list unchanged. :param int page_limit: An optional integer specifying the number of documents that you want the service to return. :param str cursor: An optional string that returns the set of documents after the previous set. Use this parameter with the `page_limit` parameter. :param str sort: An optional comma-separated list of fields in the document to sort on. You can optionally specify the sort direction by prefixing the value of the field with `-` for descending order or `+` for ascending order (the default). Currently permitted sorting fields are `created`, `user_id`, and `document_title`. :param bool include_total: An optional boolean value. If specified as `true`, the `pagination` object in the output includes a value called `total` that gives the total count of feedback created. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=list_feedback' params = { 'version': self.version, 'feedback_type': feedback_type, 'before': before, 'after': after, 'document_title': document_title, 'model_id': model_id, 'model_version': model_version, 'category_removed': category_removed, 'category_added': category_added, 'category_not_changed': category_not_changed, 'type_removed': type_removed, 'type_added': type_added, 'type_not_changed': type_not_changed, 'page_limit': page_limit, 'cursor': cursor, 'sort': sort, 'include_total': include_total } url = '/v1/feedback' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Batches ######################### def create_batch(self, function, input_credentials_file, input_bucket_location, input_bucket_name, output_credentials_file, output_bucket_location, output_bucket_name, model_id=None, input_credentials_filename=None, output_credentials_filename=None, **kwargs): """ Submit a batch-processing request. Run Compare and Comply methods over a collection of input documents. **Important:** Batch processing requires the use of the [IBM Cloud Object Storage service](https://cloud.ibm.com/docs/services/cloud-object-storage/about-cos.html#about-ibm-cloud-object-storage). The use of IBM Cloud Object Storage with Compare and Comply is discussed at [Using batch processing](https://cloud.ibm.com/docs/services/compare-comply/batching.html#before-you-batch). :param str function: The Compare and Comply method to run across the submitted input documents. :param file input_credentials_file: A JSON file containing the input Cloud Object Storage credentials. At a minimum, the credentials must enable `READ` permissions on the bucket defined by the `input_bucket_name` parameter. :param str input_bucket_location: The geographical location of the Cloud Object Storage input bucket as listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :param str input_bucket_name: The name of the Cloud Object Storage input bucket. :param file output_credentials_file: A JSON file that lists the Cloud Object Storage output credentials. At a minimum, the credentials must enable `READ` and `WRITE` permissions on the bucket defined by the `output_bucket_name` parameter. :param str output_bucket_location: The geographical location of the Cloud Object Storage output bucket as listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :param str output_bucket_name: The name of the Cloud Object Storage output bucket. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param str input_credentials_filename: The filename for input_credentials_file. :param str output_credentials_filename: The filename for output_credentials_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if function is None: raise ValueError('function must be provided') if input_credentials_file is None: raise ValueError('input_credentials_file must be provided') if input_bucket_location is None: raise ValueError('input_bucket_location must be provided') if input_bucket_name is None: raise ValueError('input_bucket_name must be provided') if output_credentials_file is None: raise ValueError('output_credentials_file must be provided') if output_bucket_location is None: raise ValueError('output_bucket_location must be provided') if output_bucket_name is None: raise ValueError('output_bucket_name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=create_batch' params = { 'version': self.version, 'function': function, 'model_id': model_id } form_data = {} if not input_credentials_filename and hasattr(input_credentials_file, 'name'): input_credentials_filename = basename(input_credentials_file.name) form_data['input_credentials_file'] = (input_credentials_filename, input_credentials_file, 'application/json') form_data['input_bucket_location'] = (None, input_bucket_location, 'text/plain') form_data['input_bucket_name'] = (None, input_bucket_name, 'text/plain') if not output_credentials_filename and hasattr(output_credentials_file, 'name'): output_credentials_filename = basename(output_credentials_file.name) form_data['output_credentials_file'] = (output_credentials_filename, output_credentials_file, 'application/json') form_data['output_bucket_location'] = (None, output_bucket_location, 'text/plain') form_data['output_bucket_name'] = (None, output_bucket_name, 'text/plain') url = '/v1/batches' response = self.request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) return response def get_batch(self, batch_id, **kwargs): """ Get information about a specific batch-processing request. Get information about a batch-processing request with a specified ID. :param str batch_id: The ID of the batch-processing request whose information you want to retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if batch_id is None: raise ValueError('batch_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=get_batch' params = {'version': self.version} url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_batches(self, **kwargs): """ List submitted batch-processing jobs. List the batch-processing jobs submitted by users. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=list_batches' params = {'version': self.version} url = '/v1/batches' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_batch(self, batch_id, action, model_id=None, **kwargs): """ Update a pending or active batch-processing request. Update a pending or active batch-processing request. You can rescan the input bucket to check for new documents or cancel a request. :param str batch_id: The ID of the batch-processing request you want to update. :param str action: The action you want to perform on the specified batch-processing request. :param str model_id: The analysis model to be used by the service. For the `/v1/element_classification` and `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if batch_id is None: raise ValueError('batch_id must be provided') if action is None: raise ValueError('action must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=compare-comply;service_version=V1;operation_id=update_batch' params = { 'version': self.version, 'action': action, 'model_id': model_id } url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) response = self.request( method='PUT', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class Address(object): """ A party's address. :attr str text: (optional) A string listing the address. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ def __init__(self, text=None, location=None): """ Initialize a Address object. :param str text: (optional) A string listing the address. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ self.text = text self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a Address object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict def __str__(self): """Return a `str` version of this Address object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class AlignedElement(object): """ AlignedElement. :attr list[ElementPair] element_pair: (optional) Identifies two elements that semantically align between the compared documents. :attr bool identical_text: (optional) Specifies whether the text is identical. :attr bool significant_elements: (optional) Indicates that the elements aligned are contractual clauses of significance. :attr list[str] provenance_ids: (optional) One or more hashed values that you can send to IBM to provide feedback or receive support. """ def __init__(self, element_pair=None, identical_text=None, significant_elements=None, provenance_ids=None): """ Initialize a AlignedElement object. :param list[ElementPair] element_pair: (optional) Identifies two elements that semantically align between the compared documents. :param bool identical_text: (optional) Specifies whether the text is identical. :param bool significant_elements: (optional) Indicates that the elements aligned are contractual clauses of significance. :param list[str] provenance_ids: (optional) One or more hashed values that you can send to IBM to provide feedback or receive support. """ self.element_pair = element_pair self.identical_text = identical_text self.significant_elements = significant_elements self.provenance_ids = provenance_ids @classmethod def _from_dict(cls, _dict): """Initialize a AlignedElement object from a json dictionary.""" args = {} if 'element_pair' in _dict: args['element_pair'] = [ ElementPair._from_dict(x) for x in (_dict.get('element_pair')) ] if 'identical_text' in _dict: args['identical_text'] = _dict.get('identical_text') if 'significant_elements' in _dict: args['significant_elements'] = _dict.get('significant_elements') if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'element_pair') and self.element_pair is not None: _dict['element_pair'] = [x._to_dict() for x in self.element_pair] if hasattr(self, 'identical_text') and self.identical_text is not None: _dict['identical_text'] = self.identical_text if hasattr(self, 'significant_elements' ) and self.significant_elements is not None: _dict['significant_elements'] = self.significant_elements if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids return _dict def __str__(self): """Return a `str` version of this AlignedElement object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Attribute(object): """ List of document attributes. :attr str type: (optional) The type of attribute. :attr str text: (optional) The text associated with the attribute. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ def __init__(self, type=None, text=None, location=None): """ Initialize a Attribute object. :param str type: (optional) The type of attribute. :param str text: (optional) The text associated with the attribute. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ self.type = type self.text = text self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a Attribute object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict def __str__(self): """Return a `str` version of this Attribute object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class BatchStatus(object): """ The batch-request status. :attr str function: (optional) The method to be run against the documents. Possible values are `html_conversion`, `element_classification`, and `tables`. :attr str input_bucket_location: (optional) The geographical location of the Cloud Object Storage input bucket as listed on the **Endpoint** tab of your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :attr str input_bucket_name: (optional) The name of the Cloud Object Storage input bucket. :attr str output_bucket_location: (optional) The geographical location of the Cloud Object Storage output bucket as listed on the **Endpoint** tab of your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :attr str output_bucket_name: (optional) The name of the Cloud Object Storage output bucket. :attr str batch_id: (optional) The unique identifier for the batch request. :attr DocCounts document_counts: (optional) Document counts. :attr str status: (optional) The status of the batch request. :attr datetime created: (optional) The creation time of the batch request. :attr datetime updated: (optional) The time of the most recent update to the batch request. """ def __init__(self, function=None, input_bucket_location=None, input_bucket_name=None, output_bucket_location=None, output_bucket_name=None, batch_id=None, document_counts=None, status=None, created=None, updated=None): """ Initialize a BatchStatus object. :param str function: (optional) The method to be run against the documents. Possible values are `html_conversion`, `element_classification`, and `tables`. :param str input_bucket_location: (optional) The geographical location of the Cloud Object Storage input bucket as listed on the **Endpoint** tab of your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :param str input_bucket_name: (optional) The name of the Cloud Object Storage input bucket. :param str output_bucket_location: (optional) The geographical location of the Cloud Object Storage output bucket as listed on the **Endpoint** tab of your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :param str output_bucket_name: (optional) The name of the Cloud Object Storage output bucket. :param str batch_id: (optional) The unique identifier for the batch request. :param DocCounts document_counts: (optional) Document counts. :param str status: (optional) The status of the batch request. :param datetime created: (optional) The creation time of the batch request. :param datetime updated: (optional) The time of the most recent update to the batch request. """ self.function = function self.input_bucket_location = input_bucket_location self.input_bucket_name = input_bucket_name self.output_bucket_location = output_bucket_location self.output_bucket_name = output_bucket_name self.batch_id = batch_id self.document_counts = document_counts self.status = status self.created = created self.updated = updated @classmethod def _from_dict(cls, _dict): """Initialize a BatchStatus object from a json dictionary.""" args = {} if 'function' in _dict: args['function'] = _dict.get('function') if 'input_bucket_location' in _dict: args['input_bucket_location'] = _dict.get('input_bucket_location') if 'input_bucket_name' in _dict: args['input_bucket_name'] = _dict.get('input_bucket_name') if 'output_bucket_location' in _dict: args['output_bucket_location'] = _dict.get('output_bucket_location') if 'output_bucket_name' in _dict: args['output_bucket_name'] = _dict.get('output_bucket_name') if 'batch_id' in _dict: args['batch_id'] = _dict.get('batch_id') if 'document_counts' in _dict: args['document_counts'] = DocCounts._from_dict( _dict.get('document_counts')) if 'status' in _dict: args['status'] = _dict.get('status') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'function') and self.function is not None: _dict['function'] = self.function if hasattr(self, 'input_bucket_location' ) and self.input_bucket_location is not None: _dict['input_bucket_location'] = self.input_bucket_location if hasattr(self, 'input_bucket_name') and self.input_bucket_name is not None: _dict['input_bucket_name'] = self.input_bucket_name if hasattr(self, 'output_bucket_location' ) and self.output_bucket_location is not None: _dict['output_bucket_location'] = self.output_bucket_location if hasattr( self, 'output_bucket_name') and self.output_bucket_name is not None: _dict['output_bucket_name'] = self.output_bucket_name if hasattr(self, 'batch_id') and self.batch_id is not None: _dict['batch_id'] = self.batch_id if hasattr(self, 'document_counts') and self.document_counts is not None: _dict['document_counts'] = self.document_counts._to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) return _dict def __str__(self): """Return a `str` version of this BatchStatus object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Batches(object): """ The results of a successful `GET /v1/batches` request. :attr list[BatchStatus] batches: (optional) A list of the status of all batch requests. """ def __init__(self, batches=None): """ Initialize a Batches object. :param list[BatchStatus] batches: (optional) A list of the status of all batch requests. """ self.batches = batches @classmethod def _from_dict(cls, _dict): """Initialize a Batches object from a json dictionary.""" args = {} if 'batches' in _dict: args['batches'] = [ BatchStatus._from_dict(x) for x in (_dict.get('batches')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'batches') and self.batches is not None: _dict['batches'] = [x._to_dict() for x in self.batches] return _dict def __str__(self): """Return a `str` version of this Batches object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class BodyCells(object): """ Cells that are not table header, column header, or row header cells. :attr str cell_id: (optional) A string value in the format `columnHeader-x-y`, where `x` and `y` are the begin and end offsets of this column header cell in the input document. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The textual contents of this cell from the input document without associated markup content. :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :attr int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :attr int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. :attr list[str] row_header_ids: (optional) An array of values, each being the `id` value of a row header that is applicable to this body cell. :attr list[str] row_header_texts: (optional) An array of values, each being the `text` value of a row header that is applicable to this body cell. :attr list[str] row_header_texts_normalized: (optional) If you provide customization input, the normalized version of the row header texts according to the customization; otherwise, the same value as `row_header_texts`. :attr list[str] column_header_ids: (optional) An array of values, each being the `id` value of a column header that is applicable to the current cell. :attr list[str] column_header_texts: (optional) An array of values, each being the `text` value of a column header that is applicable to the current cell. :attr list[str] column_header_texts_normalized: (optional) If you provide customization input, the normalized version of the column header texts according to the customization; otherwise, the same value as `column_header_texts`. :attr list[Attribute] attributes: (optional) """ def __init__(self, cell_id=None, location=None, text=None, row_index_begin=None, row_index_end=None, column_index_begin=None, column_index_end=None, row_header_ids=None, row_header_texts=None, row_header_texts_normalized=None, column_header_ids=None, column_header_texts=None, column_header_texts_normalized=None, attributes=None): """ Initialize a BodyCells object. :param str cell_id: (optional) A string value in the format `columnHeader-x-y`, where `x` and `y` are the begin and end offsets of this column header cell in the input document. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. :param list[str] row_header_ids: (optional) An array of values, each being the `id` value of a row header that is applicable to this body cell. :param list[str] row_header_texts: (optional) An array of values, each being the `text` value of a row header that is applicable to this body cell. :param list[str] row_header_texts_normalized: (optional) If you provide customization input, the normalized version of the row header texts according to the customization; otherwise, the same value as `row_header_texts`. :param list[str] column_header_ids: (optional) An array of values, each being the `id` value of a column header that is applicable to the current cell. :param list[str] column_header_texts: (optional) An array of values, each being the `text` value of a column header that is applicable to the current cell. :param list[str] column_header_texts_normalized: (optional) If you provide customization input, the normalized version of the column header texts according to the customization; otherwise, the same value as `column_header_texts`. :param list[Attribute] attributes: (optional) """ self.cell_id = cell_id self.location = location self.text = text self.row_index_begin = row_index_begin self.row_index_end = row_index_end self.column_index_begin = column_index_begin self.column_index_end = column_index_end self.row_header_ids = row_header_ids self.row_header_texts = row_header_texts self.row_header_texts_normalized = row_header_texts_normalized self.column_header_ids = column_header_ids self.column_header_texts = column_header_texts self.column_header_texts_normalized = column_header_texts_normalized self.attributes = attributes @classmethod def _from_dict(cls, _dict): """Initialize a BodyCells object from a json dictionary.""" args = {} if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'row_index_begin' in _dict: args['row_index_begin'] = _dict.get('row_index_begin') if 'row_index_end' in _dict: args['row_index_end'] = _dict.get('row_index_end') if 'column_index_begin' in _dict: args['column_index_begin'] = _dict.get('column_index_begin') if 'column_index_end' in _dict: args['column_index_end'] = _dict.get('column_index_end') if 'row_header_ids' in _dict: args['row_header_ids'] = _dict.get('row_header_ids') if 'row_header_texts' in _dict: args['row_header_texts'] = _dict.get('row_header_texts') if 'row_header_texts_normalized' in _dict: args['row_header_texts_normalized'] = _dict.get( 'row_header_texts_normalized') if 'column_header_ids' in _dict: args['column_header_ids'] = _dict.get('column_header_ids') if 'column_header_texts' in _dict: args['column_header_texts'] = _dict.get('column_header_texts') if 'column_header_texts_normalized' in _dict: args['column_header_texts_normalized'] = _dict.get( 'column_header_texts_normalized') if 'attributes' in _dict: args['attributes'] = [ Attribute._from_dict(x) for x in (_dict.get('attributes')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'row_index_begin') and self.row_index_begin is not None: _dict['row_index_begin'] = self.row_index_begin if hasattr(self, 'row_index_end') and self.row_index_end is not None: _dict['row_index_end'] = self.row_index_end if hasattr( self, 'column_index_begin') and self.column_index_begin is not None: _dict['column_index_begin'] = self.column_index_begin if hasattr(self, 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: _dict['row_header_ids'] = self.row_header_ids if hasattr(self, 'row_header_texts') and self.row_header_texts is not None: _dict['row_header_texts'] = self.row_header_texts if hasattr(self, 'row_header_texts_normalized' ) and self.row_header_texts_normalized is not None: _dict[ 'row_header_texts_normalized'] = self.row_header_texts_normalized if hasattr(self, 'column_header_ids') and self.column_header_ids is not None: _dict['column_header_ids'] = self.column_header_ids if hasattr( self, 'column_header_texts') and self.column_header_texts is not None: _dict['column_header_texts'] = self.column_header_texts if hasattr(self, 'column_header_texts_normalized' ) and self.column_header_texts_normalized is not None: _dict[ 'column_header_texts_normalized'] = self.column_header_texts_normalized if hasattr(self, 'attributes') and self.attributes is not None: _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict def __str__(self): """Return a `str` version of this BodyCells object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Category(object): """ Information defining an element's subject matter. :attr str label: (optional) The category of the associated element. :attr list[str] provenance_ids: (optional) One or more hashed values that you can send to IBM to provide feedback or receive support. """ def __init__(self, label=None, provenance_ids=None): """ Initialize a Category object. :param str label: (optional) The category of the associated element. :param list[str] provenance_ids: (optional) One or more hashed values that you can send to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @classmethod def _from_dict(cls, _dict): """Initialize a Category object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = _dict.get('label') if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids return _dict def __str__(self): """Return a `str` version of this Category object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassifyReturn(object): """ The analysis of objects returned by the `/v1/element_classification` method. :attr Document document: (optional) Basic information about the input document. :attr str model_id: (optional) The analysis model used to classify the input document. For the `/v1/element_classification` method, the only valid value is `contracts`. :attr str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. :attr list[Element] elements: (optional) Document elements identified by the service. :attr list[Tables] tables: (optional) Definition of tables identified in the input document. :attr DocStructure document_structure: (optional) The structure of the input document. :attr list[Parties] parties: (optional) Definitions of the parties identified in the input document. :attr list[EffectiveDates] effective_dates: (optional) The effective dates of the input document. :attr list[ContractAmts] contract_amounts: (optional) The monetary amounts identified in the input document. :attr list[TerminationDates] termination_dates: (optional) The input document's termination dates. """ def __init__(self, document=None, model_id=None, model_version=None, elements=None, tables=None, document_structure=None, parties=None, effective_dates=None, contract_amounts=None, termination_dates=None): """ Initialize a ClassifyReturn object. :param Document document: (optional) Basic information about the input document. :param str model_id: (optional) The analysis model used to classify the input document. For the `/v1/element_classification` method, the only valid value is `contracts`. :param str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. :param list[Element] elements: (optional) Document elements identified by the service. :param list[Tables] tables: (optional) Definition of tables identified in the input document. :param DocStructure document_structure: (optional) The structure of the input document. :param list[Parties] parties: (optional) Definitions of the parties identified in the input document. :param list[EffectiveDates] effective_dates: (optional) The effective dates of the input document. :param list[ContractAmts] contract_amounts: (optional) The monetary amounts identified in the input document. :param list[TerminationDates] termination_dates: (optional) The input document's termination dates. """ self.document = document self.model_id = model_id self.model_version = model_version self.elements = elements self.tables = tables self.document_structure = document_structure self.parties = parties self.effective_dates = effective_dates self.contract_amounts = contract_amounts self.termination_dates = termination_dates @classmethod def _from_dict(cls, _dict): """Initialize a ClassifyReturn object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = Document._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'elements' in _dict: args['elements'] = [ Element._from_dict(x) for x in (_dict.get('elements')) ] if 'tables' in _dict: args['tables'] = [ Tables._from_dict(x) for x in (_dict.get('tables')) ] if 'document_structure' in _dict: args['document_structure'] = DocStructure._from_dict( _dict.get('document_structure')) if 'parties' in _dict: args['parties'] = [ Parties._from_dict(x) for x in (_dict.get('parties')) ] if 'effective_dates' in _dict: args['effective_dates'] = [ EffectiveDates._from_dict(x) for x in (_dict.get('effective_dates')) ] if 'contract_amounts' in _dict: args['contract_amounts'] = [ ContractAmts._from_dict(x) for x in (_dict.get('contract_amounts')) ] if 'termination_dates' in _dict: args['termination_dates'] = [ TerminationDates._from_dict(x) for x in (_dict.get('termination_dates')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document._to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'elements') and self.elements is not None: _dict['elements'] = [x._to_dict() for x in self.elements] if hasattr(self, 'tables') and self.tables is not None: _dict['tables'] = [x._to_dict() for x in self.tables] if hasattr( self, 'document_structure') and self.document_structure is not None: _dict['document_structure'] = self.document_structure._to_dict() if hasattr(self, 'parties') and self.parties is not None: _dict['parties'] = [x._to_dict() for x in self.parties] if hasattr(self, 'effective_dates') and self.effective_dates is not None: _dict['effective_dates'] = [ x._to_dict() for x in self.effective_dates ] if hasattr(self, 'contract_amounts') and self.contract_amounts is not None: _dict['contract_amounts'] = [ x._to_dict() for x in self.contract_amounts ] if hasattr(self, 'termination_dates') and self.termination_dates is not None: _dict['termination_dates'] = [ x._to_dict() for x in self.termination_dates ] return _dict def __str__(self): """Return a `str` version of this ClassifyReturn object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ColumnHeaders(object): """ Column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. :attr str cell_id: (optional) A string value in the format `columnHeader-x-y`, where `x` and `y` are the begin and end offsets of this column header cell in the input document. :attr object location: (optional) The location of the column header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :attr str text: (optional) The textual contents of this cell from the input document without associated markup content. :attr str text_normalized: (optional) If you provide customization input, the normalized version of the cell text according to the customization; otherwise, the same value as `text`. :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :attr int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :attr int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ def __init__(self, cell_id=None, location=None, text=None, text_normalized=None, row_index_begin=None, row_index_end=None, column_index_begin=None, column_index_end=None): """ Initialize a ColumnHeaders object. :param str cell_id: (optional) A string value in the format `columnHeader-x-y`, where `x` and `y` are the begin and end offsets of this column header cell in the input document. :param object location: (optional) The location of the column header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. :param str text_normalized: (optional) If you provide customization input, the normalized version of the cell text according to the customization; otherwise, the same value as `text`. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ self.cell_id = cell_id self.location = location self.text = text self.text_normalized = text_normalized self.row_index_begin = row_index_begin self.row_index_end = row_index_end self.column_index_begin = column_index_begin self.column_index_end = column_index_end @classmethod def _from_dict(cls, _dict): """Initialize a ColumnHeaders object from a json dictionary.""" args = {} if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: args['location'] = _dict.get('location') if 'text' in _dict: args['text'] = _dict.get('text') if 'text_normalized' in _dict: args['text_normalized'] = _dict.get('text_normalized') if 'row_index_begin' in _dict: args['row_index_begin'] = _dict.get('row_index_begin') if 'row_index_end' in _dict: args['row_index_end'] = _dict.get('row_index_end') if 'column_index_begin' in _dict: args['column_index_begin'] = _dict.get('column_index_begin') if 'column_index_end' in _dict: args['column_index_end'] = _dict.get('column_index_end') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'text_normalized') and self.text_normalized is not None: _dict['text_normalized'] = self.text_normalized if hasattr(self, 'row_index_begin') and self.row_index_begin is not None: _dict['row_index_begin'] = self.row_index_begin if hasattr(self, 'row_index_end') and self.row_index_end is not None: _dict['row_index_end'] = self.row_index_end if hasattr( self, 'column_index_begin') and self.column_index_begin is not None: _dict['column_index_begin'] = self.column_index_begin if hasattr(self, 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end return _dict def __str__(self): """Return a `str` version of this ColumnHeaders object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CompareReturn(object): """ The comparison of the two submitted documents. :attr list[Document] documents: (optional) Information about the documents being compared. :attr list[AlignedElement] aligned_elements: (optional) A list of pairs of elements that semantically align between the compared documents. :attr list[UnalignedElement] unaligned_elements: (optional) A list of elements that do not semantically align between the compared documents. :attr str model_id: (optional) The analysis model used to classify the input document. For the `/v1/element_classification` method, the only valid value is `contracts`. :attr str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. """ def __init__(self, documents=None, aligned_elements=None, unaligned_elements=None, model_id=None, model_version=None): """ Initialize a CompareReturn object. :param list[Document] documents: (optional) Information about the documents being compared. :param list[AlignedElement] aligned_elements: (optional) A list of pairs of elements that semantically align between the compared documents. :param list[UnalignedElement] unaligned_elements: (optional) A list of elements that do not semantically align between the compared documents. :param str model_id: (optional) The analysis model used to classify the input document. For the `/v1/element_classification` method, the only valid value is `contracts`. :param str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. """ self.documents = documents self.aligned_elements = aligned_elements self.unaligned_elements = unaligned_elements self.model_id = model_id self.model_version = model_version @classmethod def _from_dict(cls, _dict): """Initialize a CompareReturn object from a json dictionary.""" args = {} if 'documents' in _dict: args['documents'] = [ Document._from_dict(x) for x in (_dict.get('documents')) ] if 'aligned_elements' in _dict: args['aligned_elements'] = [ AlignedElement._from_dict(x) for x in (_dict.get('aligned_elements')) ] if 'unaligned_elements' in _dict: args['unaligned_elements'] = [ UnalignedElement._from_dict(x) for x in (_dict.get('unaligned_elements')) ] if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: _dict['documents'] = [x._to_dict() for x in self.documents] if hasattr(self, 'aligned_elements') and self.aligned_elements is not None: _dict['aligned_elements'] = [ x._to_dict() for x in self.aligned_elements ] if hasattr( self, 'unaligned_elements') and self.unaligned_elements is not None: _dict['unaligned_elements'] = [ x._to_dict() for x in self.unaligned_elements ] if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version return _dict def __str__(self): """Return a `str` version of this CompareReturn object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Contact(object): """ A contact. :attr str name: (optional) A string listing the name of the contact. :attr str role: (optional) A string listing the role of the contact. """ def __init__(self, name=None, role=None): """ Initialize a Contact object. :param str name: (optional) A string listing the name of the contact. :param str role: (optional) A string listing the role of the contact. """ self.name = name self.role = role @classmethod def _from_dict(cls, _dict): """Initialize a Contact object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') if 'role' in _dict: args['role'] = _dict.get('role') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'role') and self.role is not None: _dict['role'] = self.role return _dict def __str__(self): """Return a `str` version of this Contact object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ContractAmts(object): """ A monetary amount identified in the input document. :attr str text: (optional) The monetary amount. :attr str confidence_level: (optional) The confidence level in the identification of the contract amount. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ def __init__(self, text=None, confidence_level=None, location=None): """ Initialize a ContractAmts object. :param str text: (optional) The monetary amount. :param str confidence_level: (optional) The confidence level in the identification of the contract amount. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ self.text = text self.confidence_level = confidence_level self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a ContractAmts object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'confidence_level') and self.confidence_level is not None: _dict['confidence_level'] = self.confidence_level if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict def __str__(self): """Return a `str` version of this ContractAmts object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocCounts(object): """ Document counts. :attr int total: (optional) Total number of documents. :attr int pending: (optional) Number of pending documents. :attr int successful: (optional) Number of documents successfully processed. :attr int failed: (optional) Number of documents not successfully processed. """ def __init__(self, total=None, pending=None, successful=None, failed=None): """ Initialize a DocCounts object. :param int total: (optional) Total number of documents. :param int pending: (optional) Number of pending documents. :param int successful: (optional) Number of documents successfully processed. :param int failed: (optional) Number of documents not successfully processed. """ self.total = total self.pending = pending self.successful = successful self.failed = failed @classmethod def _from_dict(cls, _dict): """Initialize a DocCounts object from a json dictionary.""" args = {} if 'total' in _dict: args['total'] = _dict.get('total') if 'pending' in _dict: args['pending'] = _dict.get('pending') if 'successful' in _dict: args['successful'] = _dict.get('successful') if 'failed' in _dict: args['failed'] = _dict.get('failed') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'total') and self.total is not None: _dict['total'] = self.total if hasattr(self, 'pending') and self.pending is not None: _dict['pending'] = self.pending if hasattr(self, 'successful') and self.successful is not None: _dict['successful'] = self.successful if hasattr(self, 'failed') and self.failed is not None: _dict['failed'] = self.failed return _dict def __str__(self): """Return a `str` version of this DocCounts object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocInfo(object): """ Information about the parsed input document. :attr str html: (optional) The full text of the parsed document in HTML format. :attr str title: (optional) The title of the parsed document. If the service did not detect a title, the value of this element is `null`. :attr str hash: (optional) The MD5 hash of the input document. """ def __init__(self, html=None, title=None, hash=None): """ Initialize a DocInfo object. :param str html: (optional) The full text of the parsed document in HTML format. :param str title: (optional) The title of the parsed document. If the service did not detect a title, the value of this element is `null`. :param str hash: (optional) The MD5 hash of the input document. """ self.html = html self.title = title self.hash = hash @classmethod def _from_dict(cls, _dict): """Initialize a DocInfo object from a json dictionary.""" args = {} if 'html' in _dict: args['html'] = _dict.get('html') if 'title' in _dict: args['title'] = _dict.get('title') if 'hash' in _dict: args['hash'] = _dict.get('hash') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'html') and self.html is not None: _dict['html'] = self.html if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'hash') and self.hash is not None: _dict['hash'] = self.hash return _dict def __str__(self): """Return a `str` version of this DocInfo object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocStructure(object): """ The structure of the input document. :attr list[SectionTitles] section_titles: (optional) An array containing one object per section or subsection identified in the input document. :attr list[LeadingSentence] leading_sentences: (optional) An array containing one object per section or subsection, in parallel with the `section_titles` array, that details the leading sentences in the corresponding section or subsection. """ def __init__(self, section_titles=None, leading_sentences=None): """ Initialize a DocStructure object. :param list[SectionTitles] section_titles: (optional) An array containing one object per section or subsection identified in the input document. :param list[LeadingSentence] leading_sentences: (optional) An array containing one object per section or subsection, in parallel with the `section_titles` array, that details the leading sentences in the corresponding section or subsection. """ self.section_titles = section_titles self.leading_sentences = leading_sentences @classmethod def _from_dict(cls, _dict): """Initialize a DocStructure object from a json dictionary.""" args = {} if 'section_titles' in _dict: args['section_titles'] = [ SectionTitles._from_dict(x) for x in (_dict.get('section_titles')) ] if 'leading_sentences' in _dict: args['leading_sentences'] = [ LeadingSentence._from_dict(x) for x in (_dict.get('leading_sentences')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'section_titles') and self.section_titles is not None: _dict['section_titles'] = [ x._to_dict() for x in self.section_titles ] if hasattr(self, 'leading_sentences') and self.leading_sentences is not None: _dict['leading_sentences'] = [ x._to_dict() for x in self.leading_sentences ] return _dict def __str__(self): """Return a `str` version of this DocStructure object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Document(object): """ Basic information about the input document. :attr str title: (optional) Document title, if detected. :attr str html: (optional) The input document converted into HTML format. :attr str hash: (optional) The MD5 hash value of the input document. :attr str label: (optional) The label applied to the input document with the calling method's `file_1_label` or `file_2_label` value. This field is specified only in the output of the **Comparing two documents** method. """ def __init__(self, title=None, html=None, hash=None, label=None): """ Initialize a Document object. :param str title: (optional) Document title, if detected. :param str html: (optional) The input document converted into HTML format. :param str hash: (optional) The MD5 hash value of the input document. :param str label: (optional) The label applied to the input document with the calling method's `file_1_label` or `file_2_label` value. This field is specified only in the output of the **Comparing two documents** method. """ self.title = title self.html = html self.hash = hash self.label = label @classmethod def _from_dict(cls, _dict): """Initialize a Document object from a json dictionary.""" args = {} if 'title' in _dict: args['title'] = _dict.get('title') if 'html' in _dict: args['html'] = _dict.get('html') if 'hash' in _dict: args['hash'] = _dict.get('hash') if 'label' in _dict: args['label'] = _dict.get('label') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'html') and self.html is not None: _dict['html'] = self.html if hasattr(self, 'hash') and self.hash is not None: _dict['hash'] = self.hash if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label return _dict def __str__(self): """Return a `str` version of this Document object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EffectiveDates(object): """ An effective date. :attr str text: (optional) The effective date, listed as a string. :attr str confidence_level: (optional) The confidence level in the identification of the effective date. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ def __init__(self, text=None, confidence_level=None, location=None): """ Initialize a EffectiveDates object. :param str text: (optional) The effective date, listed as a string. :param str confidence_level: (optional) The confidence level in the identification of the effective date. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ self.text = text self.confidence_level = confidence_level self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a EffectiveDates object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'confidence_level') and self.confidence_level is not None: _dict['confidence_level'] = self.confidence_level if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict def __str__(self): """Return a `str` version of this EffectiveDates object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Element(object): """ A component part of the document. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The text of the element. :attr list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :attr list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr list[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, location=None, text=None, types=None, categories=None, attributes=None): """ Initialize a Element object. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The text of the element. :param list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :param list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param list[Attribute] attributes: (optional) List of document attributes. """ self.location = location self.text = text self.types = types self.categories = categories self.attributes = attributes @classmethod def _from_dict(cls, _dict): """Initialize a Element object from a json dictionary.""" args = {} if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) ] if 'categories' in _dict: args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] if 'attributes' in _dict: args['attributes'] = [ Attribute._from_dict(x) for x in (_dict.get('attributes')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] if hasattr(self, 'attributes') and self.attributes is not None: _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict def __str__(self): """Return a `str` version of this Element object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ElementLocations(object): """ A list of `begin` and `end` indexes that indicate the locations of the elements in the input document. :attr int begin: (optional) An integer that indicates the starting position of the element in the input document. :attr int end: (optional) An integer that indicates the ending position of the element in the input document. """ def __init__(self, begin=None, end=None): """ Initialize a ElementLocations object. :param int begin: (optional) An integer that indicates the starting position of the element in the input document. :param int end: (optional) An integer that indicates the ending position of the element in the input document. """ self.begin = begin self.end = end @classmethod def _from_dict(cls, _dict): """Initialize a ElementLocations object from a json dictionary.""" args = {} if 'begin' in _dict: args['begin'] = _dict.get('begin') if 'end' in _dict: args['end'] = _dict.get('end') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'begin') and self.begin is not None: _dict['begin'] = self.begin if hasattr(self, 'end') and self.end is not None: _dict['end'] = self.end return _dict def __str__(self): """Return a `str` version of this ElementLocations object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ElementPair(object): """ Details of semantically aligned elements. :attr str document_label: (optional) The label of the document (that is, the value of either the `file_1_label` or `file_2_label` parameters) in which the element occurs. :attr str text: (optional) The text of the element. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :attr list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr list[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, document_label=None, text=None, location=None, types=None, categories=None, attributes=None): """ Initialize a ElementPair object. :param str document_label: (optional) The label of the document (that is, the value of either the `file_1_label` or `file_2_label` parameters) in which the element occurs. :param str text: (optional) The text of the element. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :param list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param list[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label self.text = text self.location = location self.types = types self.categories = categories self.attributes = attributes @classmethod def _from_dict(cls, _dict): """Initialize a ElementPair object from a json dictionary.""" args = {} if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) ] if 'categories' in _dict: args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] if 'attributes' in _dict: args['attributes'] = [ Attribute._from_dict(x) for x in (_dict.get('attributes')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_label') and self.document_label is not None: _dict['document_label'] = self.document_label if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] if hasattr(self, 'attributes') and self.attributes is not None: _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict def __str__(self): """Return a `str` version of this ElementPair object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FeedbackDataInput(object): """ Feedback data for submission. :attr str feedback_type: The type of feedback. The only permitted value is `element_classification`. :attr ShortDoc document: (optional) Brief information about the input document. :attr str model_id: (optional) An optional string identifying the model ID. The only permitted value is `contracts`. :attr str model_version: (optional) An optional string identifying the version of the model used. :attr Location location: The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr str text: The text on which to submit feedback. :attr OriginalLabelsIn original_labels: The original labeling from the input document, without the submitted feedback. :attr UpdatedLabelsIn updated_labels: The updated labeling from the input document, accounting for the submitted feedback. """ def __init__(self, feedback_type, location, text, original_labels, updated_labels, document=None, model_id=None, model_version=None): """ Initialize a FeedbackDataInput object. :param str feedback_type: The type of feedback. The only permitted value is `element_classification`. :param Location location: The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param str text: The text on which to submit feedback. :param OriginalLabelsIn original_labels: The original labeling from the input document, without the submitted feedback. :param UpdatedLabelsIn updated_labels: The updated labeling from the input document, accounting for the submitted feedback. :param ShortDoc document: (optional) Brief information about the input document. :param str model_id: (optional) An optional string identifying the model ID. The only permitted value is `contracts`. :param str model_version: (optional) An optional string identifying the version of the model used. """ self.feedback_type = feedback_type self.document = document self.model_id = model_id self.model_version = model_version self.location = location self.text = text self.original_labels = original_labels self.updated_labels = updated_labels @classmethod def _from_dict(cls, _dict): """Initialize a FeedbackDataInput object from a json dictionary.""" args = {} if 'feedback_type' in _dict: args['feedback_type'] = _dict.get('feedback_type') else: raise ValueError( 'Required property \'feedback_type\' not present in FeedbackDataInput JSON' ) if 'document' in _dict: args['document'] = ShortDoc._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) else: raise ValueError( 'Required property \'location\' not present in FeedbackDataInput JSON' ) if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in FeedbackDataInput JSON' ) if 'original_labels' in _dict: args['original_labels'] = OriginalLabelsIn._from_dict( _dict.get('original_labels')) else: raise ValueError( 'Required property \'original_labels\' not present in FeedbackDataInput JSON' ) if 'updated_labels' in _dict: args['updated_labels'] = UpdatedLabelsIn._from_dict( _dict.get('updated_labels')) else: raise ValueError( 'Required property \'updated_labels\' not present in FeedbackDataInput JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'feedback_type') and self.feedback_type is not None: _dict['feedback_type'] = self.feedback_type if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document._to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'original_labels') and self.original_labels is not None: _dict['original_labels'] = self.original_labels._to_dict() if hasattr(self, 'updated_labels') and self.updated_labels is not None: _dict['updated_labels'] = self.updated_labels._to_dict() return _dict def __str__(self): """Return a `str` version of this FeedbackDataInput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FeedbackDataOutput(object): """ Information returned from the `POST /v1/feedback` method. :attr str feedback_type: (optional) A string identifying the user adding the feedback. The only permitted value is `element_classification`. :attr ShortDoc document: (optional) Brief information about the input document. :attr str model_id: (optional) An optional string identifying the model ID. The only permitted value is `contracts`. :attr str model_version: (optional) An optional string identifying the version of the model used. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The text to which the feedback applies. :attr OriginalLabelsOut original_labels: (optional) The original labeling from the input document, without the submitted feedback. :attr UpdatedLabelsOut updated_labels: (optional) The updated labeling from the input document, accounting for the submitted feedback. :attr Pagination pagination: (optional) Pagination details, if required by the length of the output. """ def __init__(self, feedback_type=None, document=None, model_id=None, model_version=None, location=None, text=None, original_labels=None, updated_labels=None, pagination=None): """ Initialize a FeedbackDataOutput object. :param str feedback_type: (optional) A string identifying the user adding the feedback. The only permitted value is `element_classification`. :param ShortDoc document: (optional) Brief information about the input document. :param str model_id: (optional) An optional string identifying the model ID. The only permitted value is `contracts`. :param str model_version: (optional) An optional string identifying the version of the model used. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The text to which the feedback applies. :param OriginalLabelsOut original_labels: (optional) The original labeling from the input document, without the submitted feedback. :param UpdatedLabelsOut updated_labels: (optional) The updated labeling from the input document, accounting for the submitted feedback. :param Pagination pagination: (optional) Pagination details, if required by the length of the output. """ self.feedback_type = feedback_type self.document = document self.model_id = model_id self.model_version = model_version self.location = location self.text = text self.original_labels = original_labels self.updated_labels = updated_labels self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a FeedbackDataOutput object from a json dictionary.""" args = {} if 'feedback_type' in _dict: args['feedback_type'] = _dict.get('feedback_type') if 'document' in _dict: args['document'] = ShortDoc._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'original_labels' in _dict: args['original_labels'] = OriginalLabelsOut._from_dict( _dict.get('original_labels')) if 'updated_labels' in _dict: args['updated_labels'] = UpdatedLabelsOut._from_dict( _dict.get('updated_labels')) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'feedback_type') and self.feedback_type is not None: _dict['feedback_type'] = self.feedback_type if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document._to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'original_labels') and self.original_labels is not None: _dict['original_labels'] = self.original_labels._to_dict() if hasattr(self, 'updated_labels') and self.updated_labels is not None: _dict['updated_labels'] = self.updated_labels._to_dict() if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this FeedbackDataOutput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FeedbackDeleted(object): """ The status and message of the deletion request. :attr int status: (optional) HTTP return code. :attr str message: (optional) Status message returned from the service. """ def __init__(self, status=None, message=None): """ Initialize a FeedbackDeleted object. :param int status: (optional) HTTP return code. :param str message: (optional) Status message returned from the service. """ self.status = status self.message = message @classmethod def _from_dict(cls, _dict): """Initialize a FeedbackDeleted object from a json dictionary.""" args = {} if 'status' in _dict: args['status'] = _dict.get('status') if 'message' in _dict: args['message'] = _dict.get('message') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message return _dict def __str__(self): """Return a `str` version of this FeedbackDeleted object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FeedbackList(object): """ The results of a successful `GET /v1/feedback` request. :attr list[GetFeedback] feedback: (optional) A list of all feedback for the document. """ def __init__(self, feedback=None): """ Initialize a FeedbackList object. :param list[GetFeedback] feedback: (optional) A list of all feedback for the document. """ self.feedback = feedback @classmethod def _from_dict(cls, _dict): """Initialize a FeedbackList object from a json dictionary.""" args = {} if 'feedback' in _dict: args['feedback'] = [ GetFeedback._from_dict(x) for x in (_dict.get('feedback')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'feedback') and self.feedback is not None: _dict['feedback'] = [x._to_dict() for x in self.feedback] return _dict def __str__(self): """Return a `str` version of this FeedbackList object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FeedbackReturn(object): """ Information about the document and the submitted feedback. :attr str feedback_id: (optional) The unique ID of the feedback object. :attr str user_id: (optional) An optional string identifying the person submitting feedback. :attr str comment: (optional) An optional comment from the person submitting the feedback. :attr datetime created: (optional) Timestamp listing the creation time of the feedback submission. :attr FeedbackDataOutput feedback_data: (optional) Information returned from the `POST /v1/feedback` method. """ def __init__(self, feedback_id=None, user_id=None, comment=None, created=None, feedback_data=None): """ Initialize a FeedbackReturn object. :param str feedback_id: (optional) The unique ID of the feedback object. :param str user_id: (optional) An optional string identifying the person submitting feedback. :param str comment: (optional) An optional comment from the person submitting the feedback. :param datetime created: (optional) Timestamp listing the creation time of the feedback submission. :param FeedbackDataOutput feedback_data: (optional) Information returned from the `POST /v1/feedback` method. """ self.feedback_id = feedback_id self.user_id = user_id self.comment = comment self.created = created self.feedback_data = feedback_data @classmethod def _from_dict(cls, _dict): """Initialize a FeedbackReturn object from a json dictionary.""" args = {} if 'feedback_id' in _dict: args['feedback_id'] = _dict.get('feedback_id') if 'user_id' in _dict: args['user_id'] = _dict.get('user_id') if 'comment' in _dict: args['comment'] = _dict.get('comment') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'feedback_data' in _dict: args['feedback_data'] = FeedbackDataOutput._from_dict( _dict.get('feedback_data')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'feedback_id') and self.feedback_id is not None: _dict['feedback_id'] = self.feedback_id if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id if hasattr(self, 'comment') and self.comment is not None: _dict['comment'] = self.comment if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'feedback_data') and self.feedback_data is not None: _dict['feedback_data'] = self.feedback_data._to_dict() return _dict def __str__(self): """Return a `str` version of this FeedbackReturn object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class GetFeedback(object): """ The results of a single feedback query. :attr str feedback_id: (optional) A string uniquely identifying the feedback entry. :attr datetime created: (optional) A timestamp identifying the creation time of the feedback entry. :attr str comment: (optional) A string containing the user's comment about the feedback entry. :attr FeedbackDataOutput feedback_data: (optional) Information returned from the `POST /v1/feedback` method. """ def __init__(self, feedback_id=None, created=None, comment=None, feedback_data=None): """ Initialize a GetFeedback object. :param str feedback_id: (optional) A string uniquely identifying the feedback entry. :param datetime created: (optional) A timestamp identifying the creation time of the feedback entry. :param str comment: (optional) A string containing the user's comment about the feedback entry. :param FeedbackDataOutput feedback_data: (optional) Information returned from the `POST /v1/feedback` method. """ self.feedback_id = feedback_id self.created = created self.comment = comment self.feedback_data = feedback_data @classmethod def _from_dict(cls, _dict): """Initialize a GetFeedback object from a json dictionary.""" args = {} if 'feedback_id' in _dict: args['feedback_id'] = _dict.get('feedback_id') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'comment' in _dict: args['comment'] = _dict.get('comment') if 'feedback_data' in _dict: args['feedback_data'] = FeedbackDataOutput._from_dict( _dict.get('feedback_data')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'feedback_id') and self.feedback_id is not None: _dict['feedback_id'] = self.feedback_id if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'comment') and self.comment is not None: _dict['comment'] = self.comment if hasattr(self, 'feedback_data') and self.feedback_data is not None: _dict['feedback_data'] = self.feedback_data._to_dict() return _dict def __str__(self): """Return a `str` version of this GetFeedback object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class HTMLReturn(object): """ The HTML converted from an input document. :attr str num_pages: (optional) The number of pages in the input document. :attr str author: (optional) The author of the input document, if identified. :attr str publication_date: (optional) The publication date of the input document, if identified. :attr str title: (optional) The title of the input document, if identified. :attr str html: (optional) The HTML version of the input document. """ def __init__(self, num_pages=None, author=None, publication_date=None, title=None, html=None): """ Initialize a HTMLReturn object. :param str num_pages: (optional) The number of pages in the input document. :param str author: (optional) The author of the input document, if identified. :param str publication_date: (optional) The publication date of the input document, if identified. :param str title: (optional) The title of the input document, if identified. :param str html: (optional) The HTML version of the input document. """ self.num_pages = num_pages self.author = author self.publication_date = publication_date self.title = title self.html = html @classmethod def _from_dict(cls, _dict): """Initialize a HTMLReturn object from a json dictionary.""" args = {} if 'num_pages' in _dict: args['num_pages'] = _dict.get('num_pages') if 'author' in _dict: args['author'] = _dict.get('author') if 'publication_date' in _dict: args['publication_date'] = _dict.get('publication_date') if 'title' in _dict: args['title'] = _dict.get('title') if 'html' in _dict: args['html'] = _dict.get('html') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'num_pages') and self.num_pages is not None: _dict['num_pages'] = self.num_pages if hasattr(self, 'author') and self.author is not None: _dict['author'] = self.author if hasattr(self, 'publication_date') and self.publication_date is not None: _dict['publication_date'] = self.publication_date if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'html') and self.html is not None: _dict['html'] = self.html return _dict def __str__(self): """Return a `str` version of this HTMLReturn object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Label(object): """ A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected party. :attr str nature: The identified `nature` of the element. :attr str party: The identified `party` of the element. """ def __init__(self, nature, party): """ Initialize a Label object. :param str nature: The identified `nature` of the element. :param str party: The identified `party` of the element. """ self.nature = nature self.party = party @classmethod def _from_dict(cls, _dict): """Initialize a Label object from a json dictionary.""" args = {} if 'nature' in _dict: args['nature'] = _dict.get('nature') else: raise ValueError( 'Required property \'nature\' not present in Label JSON') if 'party' in _dict: args['party'] = _dict.get('party') else: raise ValueError( 'Required property \'party\' not present in Label JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'nature') and self.nature is not None: _dict['nature'] = self.nature if hasattr(self, 'party') and self.party is not None: _dict['party'] = self.party return _dict def __str__(self): """Return a `str` version of this Label object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LeadingSentence(object): """ The leading sentences in a section or subsection of the input document. :attr str text: (optional) The text of the leading sentence. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr list[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected leading sentences. """ def __init__(self, text=None, location=None, element_locations=None): """ Initialize a LeadingSentence object. :param str text: (optional) The text of the leading sentence. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param list[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected leading sentences. """ self.text = text self.location = location self.element_locations = element_locations @classmethod def _from_dict(cls, _dict): """Initialize a LeadingSentence object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'element_locations' in _dict: args['element_locations'] = [ ElementLocations._from_dict(x) for x in (_dict.get('element_locations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'element_locations') and self.element_locations is not None: _dict['element_locations'] = [ x._to_dict() for x in self.element_locations ] return _dict def __str__(self): """Return a `str` version of this LeadingSentence object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Location(object): """ The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr int begin: The element's `begin` index. :attr int end: The element's `end` index. """ def __init__(self, begin, end): """ Initialize a Location object. :param int begin: The element's `begin` index. :param int end: The element's `end` index. """ self.begin = begin self.end = end @classmethod def _from_dict(cls, _dict): """Initialize a Location object from a json dictionary.""" args = {} if 'begin' in _dict: args['begin'] = _dict.get('begin') else: raise ValueError( 'Required property \'begin\' not present in Location JSON') if 'end' in _dict: args['end'] = _dict.get('end') else: raise ValueError( 'Required property \'end\' not present in Location JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'begin') and self.begin is not None: _dict['begin'] = self.begin if hasattr(self, 'end') and self.end is not None: _dict['end'] = self.end return _dict def __str__(self): """Return a `str` version of this Location object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class OriginalLabelsIn(object): """ The original labeling from the input document, without the submitted feedback. :attr list[TypeLabel] types: Description of the action specified by the element and whom it affects. :attr list[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ def __init__(self, types, categories): """ Initialize a OriginalLabelsIn object. :param list[TypeLabel] types: Description of the action specified by the element and whom it affects. :param list[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @classmethod def _from_dict(cls, _dict): """Initialize a OriginalLabelsIn object from a json dictionary.""" args = {} if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) ] else: raise ValueError( 'Required property \'types\' not present in OriginalLabelsIn JSON' ) if 'categories' in _dict: args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] else: raise ValueError( 'Required property \'categories\' not present in OriginalLabelsIn JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] return _dict def __str__(self): """Return a `str` version of this OriginalLabelsIn object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class OriginalLabelsOut(object): """ The original labeling from the input document, without the submitted feedback. :attr list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :attr list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr str modification: (optional) A string identifying the type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ def __init__(self, types=None, categories=None, modification=None): """ Initialize a OriginalLabelsOut object. :param list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :param list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param str modification: (optional) A string identifying the type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ self.types = types self.categories = categories self.modification = modification @classmethod def _from_dict(cls, _dict): """Initialize a OriginalLabelsOut object from a json dictionary.""" args = {} if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) ] if 'categories' in _dict: args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] if 'modification' in _dict: args['modification'] = _dict.get('modification') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] if hasattr(self, 'modification') and self.modification is not None: _dict['modification'] = self.modification return _dict def __str__(self): """Return a `str` version of this OriginalLabelsOut object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Pagination(object): """ Pagination details, if required by the length of the output. :attr str refresh_cursor: (optional) A token identifying the current page of results. :attr str next_cursor: (optional) A token identifying the next page of results. :attr str refresh_url: (optional) The URL that returns the current page of results. :attr str next_url: (optional) The URL that returns the next page of results. :attr int total: (optional) Reserved for future use. """ def __init__(self, refresh_cursor=None, next_cursor=None, refresh_url=None, next_url=None, total=None): """ Initialize a Pagination object. :param str refresh_cursor: (optional) A token identifying the current page of results. :param str next_cursor: (optional) A token identifying the next page of results. :param str refresh_url: (optional) The URL that returns the current page of results. :param str next_url: (optional) The URL that returns the next page of results. :param int total: (optional) Reserved for future use. """ self.refresh_cursor = refresh_cursor self.next_cursor = next_cursor self.refresh_url = refresh_url self.next_url = next_url self.total = total @classmethod def _from_dict(cls, _dict): """Initialize a Pagination object from a json dictionary.""" args = {} if 'refresh_cursor' in _dict: args['refresh_cursor'] = _dict.get('refresh_cursor') if 'next_cursor' in _dict: args['next_cursor'] = _dict.get('next_cursor') if 'refresh_url' in _dict: args['refresh_url'] = _dict.get('refresh_url') if 'next_url' in _dict: args['next_url'] = _dict.get('next_url') if 'total' in _dict: args['total'] = _dict.get('total') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: _dict['refresh_cursor'] = self.refresh_cursor if hasattr(self, 'next_cursor') and self.next_cursor is not None: _dict['next_cursor'] = self.next_cursor if hasattr(self, 'refresh_url') and self.refresh_url is not None: _dict['refresh_url'] = self.refresh_url if hasattr(self, 'next_url') and self.next_url is not None: _dict['next_url'] = self.next_url if hasattr(self, 'total') and self.total is not None: _dict['total'] = self.total return _dict def __str__(self): """Return a `str` version of this Pagination object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Parties(object): """ A party and its corresponding role, including address and contact information if identified. :attr str party: (optional) A string identifying the party. :attr str importance: (optional) A string that identifies the importance of the party. :attr str role: (optional) A string identifying the party's role. :attr list[Address] addresses: (optional) List of the party's address or addresses. :attr list[Contact] contacts: (optional) List of the names and roles of contacts identified in the input document. """ def __init__(self, party=None, importance=None, role=None, addresses=None, contacts=None): """ Initialize a Parties object. :param str party: (optional) A string identifying the party. :param str importance: (optional) A string that identifies the importance of the party. :param str role: (optional) A string identifying the party's role. :param list[Address] addresses: (optional) List of the party's address or addresses. :param list[Contact] contacts: (optional) List of the names and roles of contacts identified in the input document. """ self.party = party self.importance = importance self.role = role self.addresses = addresses self.contacts = contacts @classmethod def _from_dict(cls, _dict): """Initialize a Parties object from a json dictionary.""" args = {} if 'party' in _dict: args['party'] = _dict.get('party') if 'importance' in _dict: args['importance'] = _dict.get('importance') if 'role' in _dict: args['role'] = _dict.get('role') if 'addresses' in _dict: args['addresses'] = [ Address._from_dict(x) for x in (_dict.get('addresses')) ] if 'contacts' in _dict: args['contacts'] = [ Contact._from_dict(x) for x in (_dict.get('contacts')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'party') and self.party is not None: _dict['party'] = self.party if hasattr(self, 'importance') and self.importance is not None: _dict['importance'] = self.importance if hasattr(self, 'role') and self.role is not None: _dict['role'] = self.role if hasattr(self, 'addresses') and self.addresses is not None: _dict['addresses'] = [x._to_dict() for x in self.addresses] if hasattr(self, 'contacts') and self.contacts is not None: _dict['contacts'] = [x._to_dict() for x in self.contacts] return _dict def __str__(self): """Return a `str` version of this Parties object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RowHeaders(object): """ Row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. :attr str cell_id: (optional) A string value in the format `rowHeader-x-y`, where `x` and `y` are the begin and end offsets of this row header cell in the input document. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The textual contents of this cell from the input document without associated markup content. :attr str text_normalized: (optional) If you provide customization input, the normalized version of the cell text according to the customization; otherwise, the same value as `text`. :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :attr int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :attr int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ def __init__(self, cell_id=None, location=None, text=None, text_normalized=None, row_index_begin=None, row_index_end=None, column_index_begin=None, column_index_end=None): """ Initialize a RowHeaders object. :param str cell_id: (optional) A string value in the format `rowHeader-x-y`, where `x` and `y` are the begin and end offsets of this row header cell in the input document. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. :param str text_normalized: (optional) If you provide customization input, the normalized version of the cell text according to the customization; otherwise, the same value as `text`. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ self.cell_id = cell_id self.location = location self.text = text self.text_normalized = text_normalized self.row_index_begin = row_index_begin self.row_index_end = row_index_end self.column_index_begin = column_index_begin self.column_index_end = column_index_end @classmethod def _from_dict(cls, _dict): """Initialize a RowHeaders object from a json dictionary.""" args = {} if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'text_normalized' in _dict: args['text_normalized'] = _dict.get('text_normalized') if 'row_index_begin' in _dict: args['row_index_begin'] = _dict.get('row_index_begin') if 'row_index_end' in _dict: args['row_index_end'] = _dict.get('row_index_end') if 'column_index_begin' in _dict: args['column_index_begin'] = _dict.get('column_index_begin') if 'column_index_end' in _dict: args['column_index_end'] = _dict.get('column_index_end') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'text_normalized') and self.text_normalized is not None: _dict['text_normalized'] = self.text_normalized if hasattr(self, 'row_index_begin') and self.row_index_begin is not None: _dict['row_index_begin'] = self.row_index_begin if hasattr(self, 'row_index_end') and self.row_index_end is not None: _dict['row_index_end'] = self.row_index_end if hasattr( self, 'column_index_begin') and self.column_index_begin is not None: _dict['column_index_begin'] = self.column_index_begin if hasattr(self, 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end return _dict def __str__(self): """Return a `str` version of this RowHeaders object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SectionTitle(object): """ The table's section title, if identified. :attr str text: (optional) The text of the section title, if identified. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ def __init__(self, text=None, location=None): """ Initialize a SectionTitle object. :param str text: (optional) The text of the section title, if identified. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ self.text = text self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a SectionTitle object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict def __str__(self): """Return a `str` version of this SectionTitle object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SectionTitles(object): """ An array containing one object per section or subsection detected in the input document. Sections and subsections are not nested; instead, they are flattened out and can be placed back in order by using the `begin` and `end` values of the element and the `level` value of the section. :attr str text: (optional) The text of the section title, if identified. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr int level: (optional) An integer indicating the level at which the section is located in the input document. For example, `1` represents a top-level section, `2` represents a subsection within the level `1` section, and so forth. :attr list[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected section titles. """ def __init__(self, text=None, location=None, level=None, element_locations=None): """ Initialize a SectionTitles object. :param str text: (optional) The text of the section title, if identified. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param int level: (optional) An integer indicating the level at which the section is located in the input document. For example, `1` represents a top-level section, `2` represents a subsection within the level `1` section, and so forth. :param list[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected section titles. """ self.text = text self.location = location self.level = level self.element_locations = element_locations @classmethod def _from_dict(cls, _dict): """Initialize a SectionTitles object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'level' in _dict: args['level'] = _dict.get('level') if 'element_locations' in _dict: args['element_locations'] = [ ElementLocations._from_dict(x) for x in (_dict.get('element_locations')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'level') and self.level is not None: _dict['level'] = self.level if hasattr(self, 'element_locations') and self.element_locations is not None: _dict['element_locations'] = [ x._to_dict() for x in self.element_locations ] return _dict def __str__(self): """Return a `str` version of this SectionTitles object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ShortDoc(object): """ Brief information about the input document. :attr str title: (optional) The title of the input document, if identified. :attr str hash: (optional) The MD5 hash of the input document. """ def __init__(self, title=None, hash=None): """ Initialize a ShortDoc object. :param str title: (optional) The title of the input document, if identified. :param str hash: (optional) The MD5 hash of the input document. """ self.title = title self.hash = hash @classmethod def _from_dict(cls, _dict): """Initialize a ShortDoc object from a json dictionary.""" args = {} if 'title' in _dict: args['title'] = _dict.get('title') if 'hash' in _dict: args['hash'] = _dict.get('hash') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'hash') and self.hash is not None: _dict['hash'] = self.hash return _dict def __str__(self): """Return a `str` version of this ShortDoc object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TableHeaders(object): """ The contents of the current table's header. :attr str cell_id: (optional) String value in the format `tableHeader-x-y` where `x` and `y` are the `begin` and `end` offsets, respectfully, of the cell value in the input document. :attr object location: (optional) The location of the table header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :attr str text: (optional) The textual contents of the cell from the input document without associated markup content. :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :attr int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :attr int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ def __init__(self, cell_id=None, location=None, text=None, row_index_begin=None, row_index_end=None, column_index_begin=None, column_index_end=None): """ Initialize a TableHeaders object. :param str cell_id: (optional) String value in the format `tableHeader-x-y` where `x` and `y` are the `begin` and `end` offsets, respectfully, of the cell value in the input document. :param object location: (optional) The location of the table header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :param str text: (optional) The textual contents of the cell from the input document without associated markup content. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ self.cell_id = cell_id self.location = location self.text = text self.row_index_begin = row_index_begin self.row_index_end = row_index_end self.column_index_begin = column_index_begin self.column_index_end = column_index_end @classmethod def _from_dict(cls, _dict): """Initialize a TableHeaders object from a json dictionary.""" args = {} if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: args['location'] = _dict.get('location') if 'text' in _dict: args['text'] = _dict.get('text') if 'row_index_begin' in _dict: args['row_index_begin'] = _dict.get('row_index_begin') if 'row_index_end' in _dict: args['row_index_end'] = _dict.get('row_index_end') if 'column_index_begin' in _dict: args['column_index_begin'] = _dict.get('column_index_begin') if 'column_index_end' in _dict: args['column_index_end'] = _dict.get('column_index_end') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'row_index_begin') and self.row_index_begin is not None: _dict['row_index_begin'] = self.row_index_begin if hasattr(self, 'row_index_end') and self.row_index_end is not None: _dict['row_index_end'] = self.row_index_end if hasattr( self, 'column_index_begin') and self.column_index_begin is not None: _dict['column_index_begin'] = self.column_index_begin if hasattr(self, 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end return _dict def __str__(self): """Return a `str` version of this TableHeaders object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TableReturn(object): """ The analysis of the document's tables. :attr DocInfo document: (optional) Information about the parsed input document. :attr str model_id: (optional) The ID of the model used to extract the table contents. The value for table extraction is `tables`. :attr str model_version: (optional) The version of the `tables` model ID. :attr list[Tables] tables: (optional) Definitions of the tables identified in the input document. """ def __init__(self, document=None, model_id=None, model_version=None, tables=None): """ Initialize a TableReturn object. :param DocInfo document: (optional) Information about the parsed input document. :param str model_id: (optional) The ID of the model used to extract the table contents. The value for table extraction is `tables`. :param str model_version: (optional) The version of the `tables` model ID. :param list[Tables] tables: (optional) Definitions of the tables identified in the input document. """ self.document = document self.model_id = model_id self.model_version = model_version self.tables = tables @classmethod def _from_dict(cls, _dict): """Initialize a TableReturn object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = DocInfo._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'tables' in _dict: args['tables'] = [ Tables._from_dict(x) for x in (_dict.get('tables')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document._to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'tables') and self.tables is not None: _dict['tables'] = [x._to_dict() for x in self.tables] return _dict def __str__(self): """Return a `str` version of this TableReturn object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Tables(object): """ The contents of the tables extracted from a document. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The textual contents of the current table from the input document without associated markup content. :attr SectionTitle section_title: (optional) The table's section title, if identified. :attr list[TableHeaders] table_headers: (optional) An array of table-level cells that apply as headers to all the other cells in the current table. :attr list[RowHeaders] row_headers: (optional) An array of row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. :attr list[ColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. :attr list[BodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. """ def __init__(self, location=None, text=None, section_title=None, table_headers=None, row_headers=None, column_headers=None, body_cells=None): """ Initialize a Tables object. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The textual contents of the current table from the input document without associated markup content. :param SectionTitle section_title: (optional) The table's section title, if identified. :param list[TableHeaders] table_headers: (optional) An array of table-level cells that apply as headers to all the other cells in the current table. :param list[RowHeaders] row_headers: (optional) An array of row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. :param list[ColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. :param list[BodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. """ self.location = location self.text = text self.section_title = section_title self.table_headers = table_headers self.row_headers = row_headers self.column_headers = column_headers self.body_cells = body_cells @classmethod def _from_dict(cls, _dict): """Initialize a Tables object from a json dictionary.""" args = {} if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'section_title' in _dict: args['section_title'] = SectionTitle._from_dict( _dict.get('section_title')) if 'table_headers' in _dict: args['table_headers'] = [ TableHeaders._from_dict(x) for x in (_dict.get('table_headers')) ] if 'row_headers' in _dict: args['row_headers'] = [ RowHeaders._from_dict(x) for x in (_dict.get('row_headers')) ] if 'column_headers' in _dict: args['column_headers'] = [ ColumnHeaders._from_dict(x) for x in (_dict.get('column_headers')) ] if 'body_cells' in _dict: args['body_cells'] = [ BodyCells._from_dict(x) for x in (_dict.get('body_cells')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'section_title') and self.section_title is not None: _dict['section_title'] = self.section_title._to_dict() if hasattr(self, 'table_headers') and self.table_headers is not None: _dict['table_headers'] = [x._to_dict() for x in self.table_headers] if hasattr(self, 'row_headers') and self.row_headers is not None: _dict['row_headers'] = [x._to_dict() for x in self.row_headers] if hasattr(self, 'column_headers') and self.column_headers is not None: _dict['column_headers'] = [ x._to_dict() for x in self.column_headers ] if hasattr(self, 'body_cells') and self.body_cells is not None: _dict['body_cells'] = [x._to_dict() for x in self.body_cells] return _dict def __str__(self): """Return a `str` version of this Tables object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TerminationDates(object): """ Termination dates identified in the input document. :attr str text: (optional) The termination date. :attr str confidence_level: (optional) The confidence level in the identification of the termination date. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ def __init__(self, text=None, confidence_level=None, location=None): """ Initialize a TerminationDates object. :param str text: (optional) The termination date. :param str confidence_level: (optional) The confidence level in the identification of the termination date. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ self.text = text self.confidence_level = confidence_level self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a TerminationDates object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'confidence_level') and self.confidence_level is not None: _dict['confidence_level'] = self.confidence_level if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict def __str__(self): """Return a `str` version of this TerminationDates object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TypeLabel(object): """ Identification of a specific type. :attr Label label: (optional) A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected party. :attr list[str] provenance_ids: (optional) One or more hash values that you can send to IBM to provide feedback or receive support. """ def __init__(self, label=None, provenance_ids=None): """ Initialize a TypeLabel object. :param Label label: (optional) A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected party. :param list[str] provenance_ids: (optional) One or more hash values that you can send to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @classmethod def _from_dict(cls, _dict): """Initialize a TypeLabel object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = Label._from_dict(_dict.get('label')) if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label._to_dict() if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids return _dict def __str__(self): """Return a `str` version of this TypeLabel object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class UnalignedElement(object): """ Element that does not align semantically between two compared documents. :attr str document_label: (optional) The label assigned to the document by the value of the `file_1_label` or `file_2_label` parameters on the `/v1/compare` method. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The text of the element. :attr list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :attr list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr list[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, document_label=None, location=None, text=None, types=None, categories=None, attributes=None): """ Initialize a UnalignedElement object. :param str document_label: (optional) The label assigned to the document by the value of the `file_1_label` or `file_2_label` parameters on the `/v1/compare` method. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The text of the element. :param list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :param list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param list[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label self.location = location self.text = text self.types = types self.categories = categories self.attributes = attributes @classmethod def _from_dict(cls, _dict): """Initialize a UnalignedElement object from a json dictionary.""" args = {} if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) ] if 'categories' in _dict: args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] if 'attributes' in _dict: args['attributes'] = [ Attribute._from_dict(x) for x in (_dict.get('attributes')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_label') and self.document_label is not None: _dict['document_label'] = self.document_label if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] if hasattr(self, 'attributes') and self.attributes is not None: _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict def __str__(self): """Return a `str` version of this UnalignedElement object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class UpdatedLabelsIn(object): """ The updated labeling from the input document, accounting for the submitted feedback. :attr list[TypeLabel] types: Description of the action specified by the element and whom it affects. :attr list[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ def __init__(self, types, categories): """ Initialize a UpdatedLabelsIn object. :param list[TypeLabel] types: Description of the action specified by the element and whom it affects. :param list[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @classmethod def _from_dict(cls, _dict): """Initialize a UpdatedLabelsIn object from a json dictionary.""" args = {} if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) ] else: raise ValueError( 'Required property \'types\' not present in UpdatedLabelsIn JSON' ) if 'categories' in _dict: args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] else: raise ValueError( 'Required property \'categories\' not present in UpdatedLabelsIn JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] return _dict def __str__(self): """Return a `str` version of this UpdatedLabelsIn object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class UpdatedLabelsOut(object): """ The updated labeling from the input document, accounting for the submitted feedback. :attr list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :attr list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr str modification: (optional) The type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ def __init__(self, types=None, categories=None, modification=None): """ Initialize a UpdatedLabelsOut object. :param list[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. :param list[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param str modification: (optional) The type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ self.types = types self.categories = categories self.modification = modification @classmethod def _from_dict(cls, _dict): """Initialize a UpdatedLabelsOut object from a json dictionary.""" args = {} if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) ] if 'categories' in _dict: args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] if 'modification' in _dict: args['modification'] = _dict.get('modification') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] if hasattr(self, 'modification') and self.modification is not None: _dict['modification'] = self.modification return _dict def __str__(self): """Return a `str` version of this UpdatedLabelsOut object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_classifier_v1.py0000644000076500000240000007275013451412211033111 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ IBM Watson™ Natural Language Classifier uses machine learning algorithms to return the top matching predefined classes for short text input. You create and train a classifier to connect predefined classes to example texts so that the service can apply those classes to new inputs. """ from __future__ import absolute_import import json from .watson_service import datetime_to_string, string_to_datetime from os.path import basename from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class NaturalLanguageClassifierV1(WatsonService): """The Natural Language Classifier V1 service.""" default_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' def __init__( self, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Natural Language Classifier service. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/natural-language-classifier/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='natural_language_classifier', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Natural Language Classifier') ######################### # Classify text ######################### def classify(self, classifier_id, text, **kwargs): """ Classify a phrase. Returns label information for the input. The status must be `Available` before you can use the classifier to classify text. :param str classifier_id: Classifier ID to use. :param str text: The submitted phrase. The maximum length is 2048 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural_language_classifier;service_version=V1;operation_id=classify' data = {'text': text} url = '/v1/classifiers/{0}/classify'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response def classify_collection(self, classifier_id, collection, **kwargs): """ Classify multiple phrases. Returns label information for multiple phrases. The status must be `Available` before you can use the classifier to classify text. Note that classifying Japanese texts is a beta feature. :param str classifier_id: Classifier ID to use. :param list[ClassifyInput] collection: The submitted phrases. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') if collection is None: raise ValueError('collection must be provided') collection = [self._convert_model(x, ClassifyInput) for x in collection] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural_language_classifier;service_version=V1;operation_id=classify_collection' data = {'collection': collection} url = '/v1/classifiers/{0}/classify_collection'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response ######################### # Manage classifiers ######################### def create_classifier(self, metadata, training_data, metadata_filename=None, training_data_filename=None, **kwargs): """ Create classifier. Sends data to create and train a classifier and returns information about the new classifier. :param file metadata: Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German, (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian Portuguese (`pt`), and Spanish (`es`). :param file training_data: Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see [Data preparation](https://cloud.ibm.com/docs/services/natural-language-classifier/using-your-data.html). :param str metadata_filename: The filename for training_metadata. :param str training_data_filename: The filename for training_data. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if metadata is None: raise ValueError('metadata must be provided') if training_data is None: raise ValueError('training_data must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural_language_classifier;service_version=V1;operation_id=create_classifier' form_data = {} if not metadata_filename and hasattr(metadata, 'name'): metadata_filename = basename(metadata.name) form_data['training_metadata'] = (metadata_filename, metadata, 'application/json') if not training_data_filename and hasattr(training_data, 'name'): training_data_filename = basename(training_data.name) form_data['training_data'] = (training_data_filename, training_data, 'text/csv') url = '/v1/classifiers' response = self.request( method='POST', url=url, headers=headers, files=form_data, accept_json=True) return response def delete_classifier(self, classifier_id, **kwargs): """ Delete classifier. :param str classifier_id: Classifier ID to delete. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural_language_classifier;service_version=V1;operation_id=delete_classifier' url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_classifier(self, classifier_id, **kwargs): """ Get information about a classifier. Returns status and other information about a classifier. :param str classifier_id: Classifier ID to query. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if classifier_id is None: raise ValueError('classifier_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural_language_classifier;service_version=V1;operation_id=get_classifier' url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_classifiers(self, **kwargs): """ List classifiers. Returns an empty array if no classifiers are available. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural_language_classifier;service_version=V1;operation_id=list_classifiers' url = '/v1/classifiers' response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response ############################################################################## # Models ############################################################################## class Classification(object): """ Response from the classifier for a phrase. :attr str classifier_id: (optional) Unique identifier for this classifier. :attr str url: (optional) Link to the classifier. :attr str text: (optional) The submitted phrase. :attr str top_class: (optional) The class with the highest confidence. :attr list[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ def __init__(self, classifier_id=None, url=None, text=None, top_class=None, classes=None): """ Initialize a Classification object. :param str classifier_id: (optional) Unique identifier for this classifier. :param str url: (optional) Link to the classifier. :param str text: (optional) The submitted phrase. :param str top_class: (optional) The class with the highest confidence. :param list[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ self.classifier_id = classifier_id self.url = url self.text = text self.top_class = top_class self.classes = classes @classmethod def _from_dict(cls, _dict): """Initialize a Classification object from a json dictionary.""" args = {} if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') if 'url' in _dict: args['url'] = _dict.get('url') if 'text' in _dict: args['text'] = _dict.get('text') if 'top_class' in _dict: args['top_class'] = _dict.get('top_class') if 'classes' in _dict: args['classes'] = [ ClassifiedClass._from_dict(x) for x in (_dict.get('classes')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifier_id') and self.classifier_id is not None: _dict['classifier_id'] = self.classifier_id if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'top_class') and self.top_class is not None: _dict['top_class'] = self.top_class if hasattr(self, 'classes') and self.classes is not None: _dict['classes'] = [x._to_dict() for x in self.classes] return _dict def __str__(self): """Return a `str` version of this Classification object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassificationCollection(object): """ Response from the classifier for multiple phrases. :attr str classifier_id: (optional) Unique identifier for this classifier. :attr str url: (optional) Link to the classifier. :attr list[CollectionItem] collection: (optional) An array of classifier responses for each submitted phrase. """ def __init__(self, classifier_id=None, url=None, collection=None): """ Initialize a ClassificationCollection object. :param str classifier_id: (optional) Unique identifier for this classifier. :param str url: (optional) Link to the classifier. :param list[CollectionItem] collection: (optional) An array of classifier responses for each submitted phrase. """ self.classifier_id = classifier_id self.url = url self.collection = collection @classmethod def _from_dict(cls, _dict): """Initialize a ClassificationCollection object from a json dictionary.""" args = {} if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') if 'url' in _dict: args['url'] = _dict.get('url') if 'collection' in _dict: args['collection'] = [ CollectionItem._from_dict(x) for x in (_dict.get('collection')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifier_id') and self.classifier_id is not None: _dict['classifier_id'] = self.classifier_id if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'collection') and self.collection is not None: _dict['collection'] = [x._to_dict() for x in self.collection] return _dict def __str__(self): """Return a `str` version of this ClassificationCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassifiedClass(object): """ Class and confidence. :attr float confidence: (optional) A decimal percentage that represents the confidence that Watson has in this class. Higher values represent higher confidences. :attr str class_name: (optional) Class label. """ def __init__(self, confidence=None, class_name=None): """ Initialize a ClassifiedClass object. :param float confidence: (optional) A decimal percentage that represents the confidence that Watson has in this class. Higher values represent higher confidences. :param str class_name: (optional) Class label. """ self.confidence = confidence self.class_name = class_name @classmethod def _from_dict(cls, _dict): """Initialize a ClassifiedClass object from a json dictionary.""" args = {} if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'class_name' in _dict: args['class_name'] = _dict.get('class_name') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'class_name') and self.class_name is not None: _dict['class_name'] = self.class_name return _dict def __str__(self): """Return a `str` version of this ClassifiedClass object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Classifier(object): """ A classifier for natural language phrases. :attr str name: (optional) User-supplied name for the classifier. :attr str url: Link to the classifier. :attr str status: (optional) The state of the classifier. :attr str classifier_id: Unique identifier for this classifier. :attr datetime created: (optional) Date and time (UTC) the classifier was created. :attr str status_description: (optional) Additional detail about the status. :attr str language: (optional) The language used for the classifier. """ def __init__(self, url, classifier_id, name=None, status=None, created=None, status_description=None, language=None): """ Initialize a Classifier object. :param str url: Link to the classifier. :param str classifier_id: Unique identifier for this classifier. :param str name: (optional) User-supplied name for the classifier. :param str status: (optional) The state of the classifier. :param datetime created: (optional) Date and time (UTC) the classifier was created. :param str status_description: (optional) Additional detail about the status. :param str language: (optional) The language used for the classifier. """ self.name = name self.url = url self.status = status self.classifier_id = classifier_id self.created = created self.status_description = status_description self.language = language @classmethod def _from_dict(cls, _dict): """Initialize a Classifier object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') if 'url' in _dict: args['url'] = _dict.get('url') else: raise ValueError( 'Required property \'url\' not present in Classifier JSON') if 'status' in _dict: args['status'] = _dict.get('status') if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') else: raise ValueError( 'Required property \'classifier_id\' not present in Classifier JSON' ) if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'status_description' in _dict: args['status_description'] = _dict.get('status_description') if 'language' in _dict: args['language'] = _dict.get('language') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'classifier_id') and self.classifier_id is not None: _dict['classifier_id'] = self.classifier_id if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr( self, 'status_description') and self.status_description is not None: _dict['status_description'] = self.status_description if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language return _dict def __str__(self): """Return a `str` version of this Classifier object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassifierList(object): """ List of available classifiers. :attr list[Classifier] classifiers: The classifiers available to the user. Returns an empty array if no classifiers are available. """ def __init__(self, classifiers): """ Initialize a ClassifierList object. :param list[Classifier] classifiers: The classifiers available to the user. Returns an empty array if no classifiers are available. """ self.classifiers = classifiers @classmethod def _from_dict(cls, _dict): """Initialize a ClassifierList object from a json dictionary.""" args = {} if 'classifiers' in _dict: args['classifiers'] = [ Classifier._from_dict(x) for x in (_dict.get('classifiers')) ] else: raise ValueError( 'Required property \'classifiers\' not present in ClassifierList JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifiers') and self.classifiers is not None: _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict def __str__(self): """Return a `str` version of this ClassifierList object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ClassifyInput(object): """ Request payload to classify. :attr str text: The submitted phrase. The maximum length is 2048 characters. """ def __init__(self, text): """ Initialize a ClassifyInput object. :param str text: The submitted phrase. The maximum length is 2048 characters. """ self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a ClassifyInput object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in ClassifyInput JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this ClassifyInput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CollectionItem(object): """ Response from the classifier for a phrase in a collection. :attr str text: (optional) The submitted phrase. The maximum length is 2048 characters. :attr str top_class: (optional) The class with the highest confidence. :attr list[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ def __init__(self, text=None, top_class=None, classes=None): """ Initialize a CollectionItem object. :param str text: (optional) The submitted phrase. The maximum length is 2048 characters. :param str top_class: (optional) The class with the highest confidence. :param list[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ self.text = text self.top_class = top_class self.classes = classes @classmethod def _from_dict(cls, _dict): """Initialize a CollectionItem object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'top_class' in _dict: args['top_class'] = _dict.get('top_class') if 'classes' in _dict: args['classes'] = [ ClassifiedClass._from_dict(x) for x in (_dict.get('classes')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'top_class') and self.top_class is not None: _dict['top_class'] = self.top_class if hasattr(self, 'classes') and self.classes is not None: _dict['classes'] = [x._to_dict() for x in self.classes] return _dict def __str__(self): """Return a `str` version of this CollectionItem object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/watson_service.py0000755000076500000240000005606013451407070030027 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2017 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json as json_import import platform import os from os.path import dirname, isfile, join, expanduser, abspath import requests import sys from requests.structures import CaseInsensitiveDict import dateutil.parser as date_parser from .iam_token_manager import IAMTokenManager import warnings try: from http.cookiejar import CookieJar # Python 3 except ImportError: from cookielib import CookieJar # Python 2 from .version import __version__ BEARER = 'Bearer' X_WATSON_AUTHORIZATION_TOKEN = 'X-Watson-Authorization-Token' AUTH_HEADER_DEPRECATION_MESSAGE = 'Authenticating with the X-Watson-Authorization-Token header is deprecated. The token continues to work with Cloud Foundry services, but is not supported for services that use Identity and Access Management (IAM) authentication.' ICP_PREFIX = 'icp-' APIKEY = 'apikey' URL = 'url' USERNAME = 'username' PASSWORD = 'password' IAM_APIKEY = 'iam_apikey' IAM_URL = 'iam_url' APIKEY_DEPRECATION_MESSAGE = 'Authenticating with apikey is deprecated. Move to using Identity and Access Management (IAM) authentication.' DEFAULT_CREDENTIALS_FILE_NAME = 'ibm-credentials.env' # Uncomment this to enable http debugging # try: # import http.client as http_client # except ImportError: # # Python 2 # import httplib as http_client # http_client.HTTPConnection.debuglevel = 1 def load_from_vcap_services(service_name): vcap_services = os.getenv("VCAP_SERVICES") if vcap_services is not None: services = json_import.loads(vcap_services) if service_name in services: return services[service_name][0]["credentials"] else: return None class WatsonException(Exception): """ Custom exception class for Watson Services. """ pass class WatsonApiException(WatsonException): """ Custom exception class for errors returned from Watson APIs. :param int code: The HTTP status code returned. :param str message: A message describing the error. :param dict info: A dictionary of additional information about the error. :param response httpResponse: response """ def __init__(self, code, message, info=None, httpResponse=None): # Call the base class constructor with the parameters it needs super(WatsonApiException, self).__init__(message) self.message = message self.code = code self.info = info self.httpResponse = httpResponse self.transactionId = None self.globalTransactionId = None if httpResponse is not None: self.transactionId = httpResponse.headers.get('X-DP-Watson-Tran-ID') self.globalTransactionId = httpResponse.headers.get('X-Global-Transaction-ID') def __str__(self): msg = 'Error: ' + str(self.message) + ', Code: ' + str(self.code) if self.info is not None: msg += ' , Information: ' + str(self.info) if self.transactionId is not None: msg += ' , X-dp-watson-tran-id: ' + str(self.transactionId) if self.globalTransactionId is not None: msg += ' , X-global-transaction-id: ' + str(self.globalTransactionId) return msg class WatsonInvalidArgument(WatsonException): pass def datetime_to_string(datetime): """ Serializes a datetime to a string. :param datetime: datetime value :return: string. containing iso8601 format date string """ return datetime.isoformat().replace('+00:00', 'Z') def string_to_datetime(string): """ Deserializes string to datetime. :param string: string containing datetime in iso8601 format :return: datetime. """ return date_parser.parse(string) def _cleanup_value(value): if isinstance(value, bool): return 'true' if value else 'false' return value def _cleanup_values(dictionary): if isinstance(dictionary, dict): return dict( [(k, _cleanup_value(v)) for k, v in dictionary.items()]) return dictionary def _remove_null_values(dictionary): if isinstance(dictionary, dict): return dict([(k, v) for k, v in dictionary.items() if v is not None]) return dictionary def _convert_boolean_value(value): if isinstance(value, bool): return 1 if value else 0 return value def _convert_boolean_values(dictionary): if isinstance(dictionary, dict): return dict( [(k, _convert_boolean_value(v)) for k, v in dictionary.items()]) return dictionary def _has_bad_first_or_last_char(str): return str is not None and (str.startswith('{') or str.startswith('"') or str.endswith('}') or str.endswith('"')) def get_error_message(response): """ Gets the error message from a JSON response. :return: the error message :rtype: string """ error_message = 'Unknown error' try: error_json = response.json() if 'error' in error_json: if isinstance(error_json['error'], dict) and 'description' in \ error_json['error']: error_message = error_json['error']['description'] else: error_message = error_json['error'] elif 'error_message' in error_json: error_message = error_json['error_message'] elif 'errorMessage' in error_json: error_message = error_json['errorMessage'] elif 'msg' in error_json: error_message = error_json['msg'] elif 'statusInfo' in error_json: error_message = error_json['statusInfo'] return error_message except: return response.text or error_message class DetailedResponse(object): """ Custom class for detailed response returned from Watson APIs. :param Response response: Either json response or http Response as requested. :param dict headers: A dict of response headers :param str status_code: HTTP response code """ def __init__(self, response=None, headers=None, status_code=None): self.result = response self.headers = headers self.status_code = status_code def get_result(self): return self.result def get_headers(self): return self.headers def get_status_code(self): return self.status_code def _to_dict(self): _dict = {} if hasattr(self, 'result') and self.result is not None: _dict['result'] = self.result if isinstance(self.result, dict) else 'HTTP response' if hasattr(self, 'headers') and self.headers is not None: _dict['headers'] = self.headers if hasattr(self, 'status_code') and self.status_code is not None: _dict['status_code'] = self.status_code return _dict def __str__(self): return json_import.dumps(self._to_dict(), indent=4, default=lambda o: o.__dict__) class WatsonService(object): def __init__(self, vcap_services_name, url, username=None, password=None, use_vcap_services=True, api_key=None, iam_apikey=None, iam_access_token=None, iam_url=None, display_name=None): """ Loads credentials from the VCAP_SERVICES environment variable if available, preferring credentials explicitly set in the request. If VCAP_SERVICES is not found (or use_vcap_services is set to False), username and password credentials must be specified. """ self.url = url self.jar = None self.api_key = None self.username = None self.password = None self.default_headers = None self.http_config = {} self.detailed_response = True self.iam_apikey = None self.iam_access_token = None self.iam_url = None self.token_manager = None self.verify = None # Indicates whether to ignore verifying the SSL certification if _has_bad_first_or_last_char(self.url): raise ValueError('The URL shouldn\'t start or end with curly brackets or quotes. ' 'Be sure to remove any {} and \" characters surrounding your URL') user_agent_string = 'watson-apis-python-sdk-' + __version__ # SDK version user_agent_string += ' ' + platform.system() # OS user_agent_string += ' ' + platform.release() # OS version user_agent_string += ' ' + platform.python_version() # Python version self.user_agent_header = {'user-agent': user_agent_string} # 1. Credentials are passed in constructor if api_key is not None: self.set_api_key(api_key) elif username is not None and password is not None: if username is APIKEY and not password.startswith(ICP_PREFIX): self.set_token_manager(password, iam_access_token, iam_url) else: self.set_username_and_password(username, password) elif iam_access_token is not None or iam_apikey is not None: if iam_apikey and iam_apikey.startswith(ICP_PREFIX): self.set_username_and_password(APIKEY, iam_apikey) else: self.set_token_manager(iam_apikey, iam_access_token, iam_url) # 2. Credentials from credential file if display_name and not self.username and not self.token_manager: service_name = display_name.replace(' ', '_').lower() self.load_from_credential_file(service_name) # 3. Credentials from VCAP if use_vcap_services and not self.username and not self.token_manager: self.vcap_service_credentials = load_from_vcap_services( vcap_services_name) if self.vcap_service_credentials is not None and isinstance( self.vcap_service_credentials, dict): self.url = self.vcap_service_credentials['url'] if 'username' in self.vcap_service_credentials: self.username = self.vcap_service_credentials.get('username') if 'password' in self.vcap_service_credentials: self.password = self.vcap_service_credentials.get('password') if 'apikey' in self.vcap_service_credentials: self.set_iam_apikey(self.vcap_service_credentials.get('apikey')) if 'iam_apikey' in self.vcap_service_credentials: self.set_iam_apikey(self.vcap_service_credentials.get('iam_apikey')) if 'iam_access_token' in self.vcap_service_credentials: self.set_iam_access_token(self.vcap_service_credentials.get('iam_access_token')) if (self.username is None or self.password is None)\ and self.api_key is None and self.token_manager is None: raise ValueError( 'You must specify your IAM api key or username and password service ' 'credentials (Note: these are different from your Bluemix id)') def load_from_credential_file(self, service_name, separator='='): """ Initiates the credentials based on the credential file :param str service_name: The service name :param str separator: the separator for key value pair """ # File path specified by an env variable credential_file_path = os.getenv("IBM_CREDENTIALS_FILE") # Home directory if credential_file_path is None: file_path = join(expanduser('~'), DEFAULT_CREDENTIALS_FILE_NAME) if isfile(file_path): credential_file_path = file_path # Top-level of the project directory if credential_file_path is None: file_path = join(dirname(dirname(abspath(__file__))), DEFAULT_CREDENTIALS_FILE_NAME) if isfile(file_path): credential_file_path = file_path if credential_file_path is not None: with open(credential_file_path, 'r') as fp: for line in fp: key_val = line.strip().split(separator) if len(key_val) == 2: self._set_credential_based_on_type(service_name, key_val[0].lower(), key_val[1]) def _set_credential_based_on_type(self, service_name, key, value): if service_name in key: if APIKEY in key: self.set_iam_apikey(value) elif URL in key: self.set_url(value) elif USERNAME in key: self.username = value elif PASSWORD in key: self.password = value elif IAM_APIKEY in key: self.set_iam_apikey(value) elif IAM_URL in key: self.set_iam_url(value) def set_username_and_password(self, username=None, password=None): if username == 'YOUR SERVICE USERNAME': username = None if password == 'YOUR SERVICE PASSWORD': password = None if _has_bad_first_or_last_char(username): raise ValueError('The username shouldn\'t start or end with curly brackets or quotes. ' 'Be sure to remove any {} and \" characters surrounding your username') if _has_bad_first_or_last_char(password): raise ValueError('The password shouldn\'t start or end with curly brackets or quotes. ' 'Be sure to remove any {} and \" characters surrounding your password') self.username = username self.password = password self.jar = CookieJar() def set_api_key(self, api_key): if api_key is not None: warnings.warn(APIKEY_DEPRECATION_MESSAGE) if api_key == 'YOUR API KEY': api_key = None if api_key is not None and api_key.startswith(ICP_PREFIX): self.set_username_and_password(APIKEY, api_key) return self.api_key = api_key # This would be called only for Visual recognition if self.url is self.default_url: self.set_url('https://gateway-a.watsonplatform.net/visual-recognition/api') self.jar = CookieJar() def set_token_manager(self, iam_apikey=None, iam_access_token=None, iam_url=None): if iam_apikey == 'YOUR IAM API KEY': return if _has_bad_first_or_last_char(iam_apikey): raise ValueError('The credentials shouldn\'t start or end with curly brackets or quotes. ' 'Be sure to remove any {} and \" characters surrounding your credentials') self.iam_apikey = iam_apikey self.iam_access_token = iam_access_token self.iam_url = iam_url self.token_manager = IAMTokenManager(iam_apikey, iam_access_token, iam_url) self.jar = CookieJar() def set_iam_access_token(self, iam_access_token): if self.token_manager: self.token_manager.set_access_token(iam_access_token) else: self.token_manager = IAMTokenManager(iam_access_token=iam_access_token) self.iam_access_token = iam_access_token self.jar = CookieJar() def set_iam_url(self, iam_url): if self.token_manager: self.token_manager.set_iam_url(iam_url) else: self.token_manager = IAMTokenManager(iam_url=iam_url) self.iam_url = iam_url self.jar = CookieJar() def set_iam_apikey(self, iam_apikey): if _has_bad_first_or_last_char(iam_apikey): raise ValueError('The credentials shouldn\'t start or end with curly brackets or quotes. ' 'Be sure to remove any {} and \" characters surrounding your credentials') if self.token_manager: self.token_manager.set_iam_apikey(iam_apikey) else: self.token_manager = IAMTokenManager(iam_apikey=iam_apikey) self.iam_apikey = iam_apikey self.jar = CookieJar() def set_url(self, url): if _has_bad_first_or_last_char(url): raise ValueError('The URL shouldn\'t start or end with curly brackets or quotes. ' 'Be sure to remove any {} and \" characters surrounding your URL') self.url = url def set_default_headers(self, headers): """ Set http headers to be sent in every request. :param headers: A dictionary of header names and values """ if isinstance(headers, dict): self.default_headers = headers else: raise TypeError("headers parameter must be a dictionary") def set_http_config(self, http_config): """ Sets the http client config like timeout, proxies, etc. """ if isinstance(http_config, dict): self.http_config = http_config else: raise TypeError("http_config parameter must be a dictionary") def disable_SSL_verification(self): self.verify = False def set_detailed_response(self, detailed_response): self.detailed_response = detailed_response # Could make this compute the label_id based on the variable name of the # dictionary passed in (using **kwargs), but # this might be confusing to understand. @staticmethod def unpack_id(dictionary, label_id): if isinstance(dictionary, dict) and label_id in dictionary: return dictionary[label_id] return dictionary @staticmethod def _convert_model(val, classname=None): if classname is not None and not hasattr(val, "_from_dict"): if isinstance(val, str): val = json_import.loads(val) val = classname._from_dict(dict(val)) if hasattr(val, "_to_dict"): return val._to_dict() return val @staticmethod def _convert_list(val): if isinstance(val, list): return ",".join(val) return val @staticmethod def _encode_path_vars(*args): return (requests.utils.quote(x, safe='') for x in args) @staticmethod def _get_error_info(response): """ Gets the error info (if any) from a JSON response. :return: A `dict` containing additional information about the error. :rtype: dict """ info_keys = ['code_description', 'description', 'errors', 'help', 'sub_code', 'warnings'] error_info = {} try: error_json = response.json() error_info = {k:v for k, v in error_json.items() if k in info_keys} except: pass return error_info if any(error_info) else None def request(self, method, url, accept_json=False, headers=None, params=None, json=None, data=None, files=None, **kwargs): full_url = self.url + url input_headers = _remove_null_values(headers) if headers else {} input_headers = _cleanup_values(input_headers) headers = CaseInsensitiveDict(self.user_agent_header) if self.default_headers is not None: headers.update(self.default_headers) if accept_json: headers['accept'] = 'application/json' headers.update(input_headers) if X_WATSON_AUTHORIZATION_TOKEN in headers: warnings.warn(AUTH_HEADER_DEPRECATION_MESSAGE) # Remove keys with None values params = _remove_null_values(params) params = _cleanup_values(params) json = _remove_null_values(json) data = _remove_null_values(data) files = _remove_null_values(files) if sys.version_info >= (3, 0) and isinstance(data, str): data = data.encode('utf-8') # Support versions of requests older than 2.4.2 without the json input if not data and json is not None: data = json_import.dumps(json) headers.update({'content-type': 'application/json'}) auth = None if self.token_manager: access_token = self.token_manager.get_token() headers['Authorization'] = '{0} {1}'.format(BEARER, access_token) if self.username and self.password: auth = (self.username, self.password) if self.api_key is not None: if params is None: params = {} if full_url.startswith( 'https://gateway-a.watsonplatform.net/calls'): params['apikey'] = self.api_key else: params['api_key'] = self.api_key # Use a one minute timeout when our caller doesn't give a timeout. # http://docs.python-requests.org/en/master/user/quickstart/#timeouts kwargs = dict({"timeout": 60}, **kwargs) kwargs = dict(kwargs, **self.http_config) if self.verify is not None: kwargs['verify'] = self.verify response = requests.request(method=method, url=full_url, cookies=self.jar, auth=auth, headers=headers, params=params, data=data, files=files, **kwargs) if 200 <= response.status_code <= 299: if response.status_code == 204 or method == 'HEAD': # There is no body content for a HEAD request or a 204 response return DetailedResponse(None, response.headers, response.status_code) if self.detailed_response else None if accept_json: try: response_json = response.json() except: # deserialization fails because there is no text return DetailedResponse(None, response.headers, response.status_code) if self.detailed_response else None if 'status' in response_json and response_json['status'] \ == 'ERROR': status_code = 400 error_message = 'Unknown error' if 'statusInfo' in response_json: error_message = response_json['statusInfo'] if error_message == 'invalid-api-key': status_code = 401 raise WatsonApiException(status_code, error_message, httpResponse=response) return DetailedResponse(response_json, response.headers, response.status_code) if self.detailed_response else response_json return DetailedResponse(response, response.headers, response.status_code) if self.detailed_response else response else: if response.status_code == 401: error_message = 'Unauthorized: Access is denied due to ' \ 'invalid credentials ' else: error_message = get_error_message(response) error_info = self._get_error_info(response) raise WatsonApiException(response.status_code, error_message, info=error_info, httpResponse=response) watson-developer-cloud-2.10.1/watson_developer_cloud/natural_language_understanding_v1.py0000644000076500000240000035172013451412220033627 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you request. The service cleans HTML content before analysis by default, so the results can ignore most advertisements and other unwanted content. You can create [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. """ from __future__ import absolute_import import json from .watson_service import datetime_to_string, string_to_datetime from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class NaturalLanguageUnderstandingV1(WatsonService): """The Natural Language Understanding V1 service.""" default_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' def __init__( self, version, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Natural Language Understanding service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/natural-language-understanding/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='natural-language-understanding', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Natural Language Understanding') self.version = version ######################### # Analyze ######################### def analyze(self, features, text=None, html=None, url=None, clean=None, xpath=None, fallback_to_raw=None, return_analyzed_text=None, language=None, limit_text_characters=None, **kwargs): """ Analyze text. Analyzes text, HTML, or a public webpage for the following features: - Categories - Concepts - Emotion - Entities - Keywords - Metadata - Relations - Semantic roles - Sentiment. :param Features features: Analysis features and options. :param str text: The plain text to analyze. One of the `text`, `html`, or `url` parameters is required. :param str html: The HTML file to analyze. One of the `text`, `html`, or `url` parameters is required. :param str url: The webpage to analyze. One of the `text`, `html`, or `url` parameters is required. :param bool clean: Set this to `false` to disable webpage cleaning. To learn more about webpage cleaning, see the [Analyzing webpages](https://cloud.ibm.com/docs/services/natural-language-understanding/analyzing-webpages.html) documentation. :param str xpath: An [XPath query](https://cloud.ibm.com/docs/services/natural-language-understanding/analyzing-webpages.html#xpath) to perform on `html` or `url` input. Results of the query will be appended to the cleaned webpage text before it is analyzed. To analyze only the results of the XPath query, set the `clean` parameter to `false`. :param bool fallback_to_raw: Whether to use raw HTML content if text cleaning fails. :param bool return_analyzed_text: Whether or not to return the analyzed text. :param str language: ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See [Language support](https://www.bluemix.net/docs/services/natural-language-understanding/language-support.html) for more information. :param int limit_text_characters: Sets the maximum number of characters that are processed by the service. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if features is None: raise ValueError('features must be provided') features = self._convert_model(features, Features) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural-language-understanding;service_version=V1;operation_id=analyze' params = {'version': self.version} data = { 'features': features, 'text': text, 'html': html, 'url': url, 'clean': clean, 'xpath': xpath, 'fallback_to_raw': fallback_to_raw, 'return_analyzed_text': return_analyzed_text, 'language': language, 'limit_text_characters': limit_text_characters } url = '/v1/analyze' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Manage models ######################### def delete_model(self, model_id, **kwargs): """ Delete model. Deletes a custom model. :param str model_id: Model ID of the model to delete. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if model_id is None: raise ValueError('model_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural-language-understanding;service_version=V1;operation_id=delete_model' params = {'version': self.version} url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def list_models(self, **kwargs): """ List models. Lists Watson Knowledge Studio [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) that are deployed to your Natural Language Understanding service. :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=natural-language-understanding;service_version=V1;operation_id=list_models' params = {'version': self.version} url = '/v1/models' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class AnalysisResults(object): """ Results of the analysis, organized by feature. :attr str language: (optional) Language used to analyze the text. :attr str analyzed_text: (optional) Text that was used in the analysis. :attr str retrieved_url: (optional) URL of the webpage that was analyzed. :attr Usage usage: (optional) Usage information. :attr list[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. :attr list[EntitiesResult] entities: (optional) The entities detected in the analyzed text. :attr list[KeywordsResult] keywords: (optional) The keywords from the analyzed text. :attr list[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. :attr EmotionResult emotion: (optional) The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases found in the text. :attr MetadataResult metadata: (optional) The authors, publication date, title, prominent page image, and RSS/ATOM feeds of the webpage. Supports URL and HTML input types. :attr list[RelationsResult] relations: (optional) The relationships between entities in the content. :attr list[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into `subject`, `action`, and `object` form. :attr SentimentResult sentiment: (optional) The sentiment of the content. """ def __init__(self, language=None, analyzed_text=None, retrieved_url=None, usage=None, concepts=None, entities=None, keywords=None, categories=None, emotion=None, metadata=None, relations=None, semantic_roles=None, sentiment=None): """ Initialize a AnalysisResults object. :param str language: (optional) Language used to analyze the text. :param str analyzed_text: (optional) Text that was used in the analysis. :param str retrieved_url: (optional) URL of the webpage that was analyzed. :param Usage usage: (optional) Usage information. :param list[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. :param list[EntitiesResult] entities: (optional) The entities detected in the analyzed text. :param list[KeywordsResult] keywords: (optional) The keywords from the analyzed text. :param list[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. :param EmotionResult emotion: (optional) The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases found in the text. :param MetadataResult metadata: (optional) The authors, publication date, title, prominent page image, and RSS/ATOM feeds of the webpage. Supports URL and HTML input types. :param list[RelationsResult] relations: (optional) The relationships between entities in the content. :param list[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into `subject`, `action`, and `object` form. :param SentimentResult sentiment: (optional) The sentiment of the content. """ self.language = language self.analyzed_text = analyzed_text self.retrieved_url = retrieved_url self.usage = usage self.concepts = concepts self.entities = entities self.keywords = keywords self.categories = categories self.emotion = emotion self.metadata = metadata self.relations = relations self.semantic_roles = semantic_roles self.sentiment = sentiment @classmethod def _from_dict(cls, _dict): """Initialize a AnalysisResults object from a json dictionary.""" args = {} if 'language' in _dict: args['language'] = _dict.get('language') if 'analyzed_text' in _dict: args['analyzed_text'] = _dict.get('analyzed_text') if 'retrieved_url' in _dict: args['retrieved_url'] = _dict.get('retrieved_url') if 'usage' in _dict: args['usage'] = Usage._from_dict(_dict.get('usage')) if 'concepts' in _dict: args['concepts'] = [ ConceptsResult._from_dict(x) for x in (_dict.get('concepts')) ] if 'entities' in _dict: args['entities'] = [ EntitiesResult._from_dict(x) for x in (_dict.get('entities')) ] if 'keywords' in _dict: args['keywords'] = [ KeywordsResult._from_dict(x) for x in (_dict.get('keywords')) ] if 'categories' in _dict: args['categories'] = [ CategoriesResult._from_dict(x) for x in (_dict.get('categories')) ] if 'emotion' in _dict: args['emotion'] = EmotionResult._from_dict(_dict.get('emotion')) if 'metadata' in _dict: args['metadata'] = MetadataResult._from_dict(_dict.get('metadata')) if 'relations' in _dict: args['relations'] = [ RelationsResult._from_dict(x) for x in (_dict.get('relations')) ] if 'semantic_roles' in _dict: args['semantic_roles'] = [ SemanticRolesResult._from_dict(x) for x in (_dict.get('semantic_roles')) ] if 'sentiment' in _dict: args['sentiment'] = SentimentResult._from_dict( _dict.get('sentiment')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'analyzed_text') and self.analyzed_text is not None: _dict['analyzed_text'] = self.analyzed_text if hasattr(self, 'retrieved_url') and self.retrieved_url is not None: _dict['retrieved_url'] = self.retrieved_url if hasattr(self, 'usage') and self.usage is not None: _dict['usage'] = self.usage._to_dict() if hasattr(self, 'concepts') and self.concepts is not None: _dict['concepts'] = [x._to_dict() for x in self.concepts] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = [x._to_dict() for x in self.keywords] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata._to_dict() if hasattr(self, 'relations') and self.relations is not None: _dict['relations'] = [x._to_dict() for x in self.relations] if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: _dict['semantic_roles'] = [ x._to_dict() for x in self.semantic_roles ] if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment._to_dict() return _dict def __str__(self): """Return a `str` version of this AnalysisResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Author(object): """ The author of the analyzed content. :attr str name: (optional) Name of the author. """ def __init__(self, name=None): """ Initialize a Author object. :param str name: (optional) Name of the author. """ self.name = name @classmethod def _from_dict(cls, _dict): """Initialize a Author object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name return _dict def __str__(self): """Return a `str` version of this Author object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CategoriesOptions(object): """ Returns a five-level taxonomy of the content. The top three categories are returned. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. :attr int limit: (optional) Maximum number of categories to return. """ def __init__(self, limit=None): """ Initialize a CategoriesOptions object. :param int limit: (optional) Maximum number of categories to return. """ self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a CategoriesOptions object from a json dictionary.""" args = {} if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this CategoriesOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CategoriesResult(object): """ A categorization of the analyzed text. :attr str label: (optional) The path to the category through the 5-level taxonomy hierarchy. For the complete list of categories, see the [Categories hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding/categories.html#categories-hierarchy) documentation. :attr float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. """ def __init__(self, label=None, score=None): """ Initialize a CategoriesResult object. :param str label: (optional) The path to the category through the 5-level taxonomy hierarchy. For the complete list of categories, see the [Categories hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding/categories.html#categories-hierarchy) documentation. :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. """ self.label = label self.score = score @classmethod def _from_dict(cls, _dict): """Initialize a CategoriesResult object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = _dict.get('label') if 'score' in _dict: args['score'] = _dict.get('score') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict def __str__(self): """Return a `str` version of this CategoriesResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConceptsOptions(object): """ Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. :attr int limit: (optional) Maximum number of concepts to return. """ def __init__(self, limit=None): """ Initialize a ConceptsOptions object. :param int limit: (optional) Maximum number of concepts to return. """ self.limit = limit @classmethod def _from_dict(cls, _dict): """Initialize a ConceptsOptions object from a json dictionary.""" args = {} if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict def __str__(self): """Return a `str` version of this ConceptsOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConceptsResult(object): """ The general concepts referenced or alluded to in the analyzed text. :attr str text: (optional) Name of the concept. :attr float relevance: (optional) Relevance score between 0 and 1. Higher scores indicate greater relevance. :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. """ def __init__(self, text=None, relevance=None, dbpedia_resource=None): """ Initialize a ConceptsResult object. :param str text: (optional) Name of the concept. :param float relevance: (optional) Relevance score between 0 and 1. Higher scores indicate greater relevance. :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. """ self.text = text self.relevance = relevance self.dbpedia_resource = dbpedia_resource @classmethod def _from_dict(cls, _dict): """Initialize a ConceptsResult object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'relevance' in _dict: args['relevance'] = _dict.get('relevance') if 'dbpedia_resource' in _dict: args['dbpedia_resource'] = _dict.get('dbpedia_resource') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevance if hasattr(self, 'dbpedia_resource') and self.dbpedia_resource is not None: _dict['dbpedia_resource'] = self.dbpedia_resource return _dict def __str__(self): """Return a `str` version of this ConceptsResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DeleteModelResults(object): """ Delete model results. :attr str deleted: (optional) model_id of the deleted model. """ def __init__(self, deleted=None): """ Initialize a DeleteModelResults object. :param str deleted: (optional) model_id of the deleted model. """ self.deleted = deleted @classmethod def _from_dict(cls, _dict): """Initialize a DeleteModelResults object from a json dictionary.""" args = {} if 'deleted' in _dict: args['deleted'] = _dict.get('deleted') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'deleted') and self.deleted is not None: _dict['deleted'] = self.deleted return _dict def __str__(self): """Return a `str` version of this DeleteModelResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DisambiguationResult(object): """ Disambiguation information for the entity. :attr str name: (optional) Common entity name. :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. :attr list[str] subtype: (optional) Entity subtype information. """ def __init__(self, name=None, dbpedia_resource=None, subtype=None): """ Initialize a DisambiguationResult object. :param str name: (optional) Common entity name. :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. :param list[str] subtype: (optional) Entity subtype information. """ self.name = name self.dbpedia_resource = dbpedia_resource self.subtype = subtype @classmethod def _from_dict(cls, _dict): """Initialize a DisambiguationResult object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') if 'dbpedia_resource' in _dict: args['dbpedia_resource'] = _dict.get('dbpedia_resource') if 'subtype' in _dict: args['subtype'] = _dict.get('subtype') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'dbpedia_resource') and self.dbpedia_resource is not None: _dict['dbpedia_resource'] = self.dbpedia_resource if hasattr(self, 'subtype') and self.subtype is not None: _dict['subtype'] = self.subtype return _dict def __str__(self): """Return a `str` version of this DisambiguationResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentEmotionResults(object): """ Emotion results for the document as a whole. :attr EmotionScores emotion: (optional) Emotion results for the document as a whole. """ def __init__(self, emotion=None): """ Initialize a DocumentEmotionResults object. :param EmotionScores emotion: (optional) Emotion results for the document as a whole. """ self.emotion = emotion @classmethod def _from_dict(cls, _dict): """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} if 'emotion' in _dict: args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() return _dict def __str__(self): """Return a `str` version of this DocumentEmotionResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentSentimentResults(object): """ DocumentSentimentResults. :attr str label: (optional) Indicates whether the sentiment is positive, neutral, or negative. :attr float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ def __init__(self, label=None, score=None): """ Initialize a DocumentSentimentResults object. :param str label: (optional) Indicates whether the sentiment is positive, neutral, or negative. :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ self.label = label self.score = score @classmethod def _from_dict(cls, _dict): """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = _dict.get('label') if 'score' in _dict: args['score'] = _dict.get('score') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict def __str__(self): """Return a `str` version of this DocumentSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EmotionOptions(object): """ Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. :attr bool document: (optional) Set this to `false` to hide document-level emotion results. :attr list[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ def __init__(self, document=None, targets=None): """ Initialize a EmotionOptions object. :param bool document: (optional) Set this to `false` to hide document-level emotion results. :param list[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ self.document = document self.targets = targets @classmethod def _from_dict(cls, _dict): """Initialize a EmotionOptions object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: args['targets'] = _dict.get('targets') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets return _dict def __str__(self): """Return a `str` version of this EmotionOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EmotionResult(object): """ The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases found in the text. :attr DocumentEmotionResults document: (optional) Emotion results for the document as a whole. :attr list[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ def __init__(self, document=None, targets=None): """ Initialize a EmotionResult object. :param DocumentEmotionResults document: (optional) Emotion results for the document as a whole. :param list[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ self.document = document self.targets = targets @classmethod def _from_dict(cls, _dict): """Initialize a EmotionResult object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = DocumentEmotionResults._from_dict( _dict.get('document')) if 'targets' in _dict: args['targets'] = [ TargetedEmotionResults._from_dict(x) for x in (_dict.get('targets')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document._to_dict() if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = [x._to_dict() for x in self.targets] return _dict def __str__(self): """Return a `str` version of this EmotionResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EmotionScores(object): """ EmotionScores. :attr float anger: (optional) Anger score from 0 to 1. A higher score means that the text is more likely to convey anger. :attr float disgust: (optional) Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. :attr float fear: (optional) Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. :attr float joy: (optional) Joy score from 0 to 1. A higher score means that the text is more likely to convey joy. :attr float sadness: (optional) Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. """ def __init__(self, anger=None, disgust=None, fear=None, joy=None, sadness=None): """ Initialize a EmotionScores object. :param float anger: (optional) Anger score from 0 to 1. A higher score means that the text is more likely to convey anger. :param float disgust: (optional) Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. :param float fear: (optional) Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. :param float joy: (optional) Joy score from 0 to 1. A higher score means that the text is more likely to convey joy. :param float sadness: (optional) Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. """ self.anger = anger self.disgust = disgust self.fear = fear self.joy = joy self.sadness = sadness @classmethod def _from_dict(cls, _dict): """Initialize a EmotionScores object from a json dictionary.""" args = {} if 'anger' in _dict: args['anger'] = _dict.get('anger') if 'disgust' in _dict: args['disgust'] = _dict.get('disgust') if 'fear' in _dict: args['fear'] = _dict.get('fear') if 'joy' in _dict: args['joy'] = _dict.get('joy') if 'sadness' in _dict: args['sadness'] = _dict.get('sadness') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'anger') and self.anger is not None: _dict['anger'] = self.anger if hasattr(self, 'disgust') and self.disgust is not None: _dict['disgust'] = self.disgust if hasattr(self, 'fear') and self.fear is not None: _dict['fear'] = self.fear if hasattr(self, 'joy') and self.joy is not None: _dict['joy'] = self.joy if hasattr(self, 'sadness') and self.sadness is not None: _dict['sadness'] = self.sadness return _dict def __str__(self): """Return a `str` version of this EmotionScores object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EntitiesOptions(object): """ Identifies people, cities, organizations, and other entities in the content. See [Entity types and subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding/entity-types.html). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. :attr int limit: (optional) Maximum number of entities to return. :attr bool mentions: (optional) Set this to `true` to return locations of entity mentions. :attr str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) ID to override the standard entity detection model. :attr bool sentiment: (optional) Set this to `true` to return sentiment information for detected entities. :attr bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ def __init__(self, limit=None, mentions=None, model=None, sentiment=None, emotion=None): """ Initialize a EntitiesOptions object. :param int limit: (optional) Maximum number of entities to return. :param bool mentions: (optional) Set this to `true` to return locations of entity mentions. :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) ID to override the standard entity detection model. :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected entities. :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ self.limit = limit self.mentions = mentions self.model = model self.sentiment = sentiment self.emotion = emotion @classmethod def _from_dict(cls, _dict): """Initialize a EntitiesOptions object from a json dictionary.""" args = {} if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'mentions' in _dict: args['mentions'] = _dict.get('mentions') if 'model' in _dict: args['model'] = _dict.get('model') if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: args['emotion'] = _dict.get('emotion') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit if hasattr(self, 'mentions') and self.mentions is not None: _dict['mentions'] = self.mentions if hasattr(self, 'model') and self.model is not None: _dict['model'] = self.model if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion return _dict def __str__(self): """Return a `str` version of this EntitiesOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EntitiesResult(object): """ The important people, places, geopolitical entities and other types of entities in your content. :attr str type: (optional) Entity type. :attr str text: (optional) The name of the entity. :attr float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. :attr list[EntityMention] mentions: (optional) Entity mentions and locations. :attr int count: (optional) How many times the entity was mentioned in the text. :attr EmotionScores emotion: (optional) Emotion analysis results for the entity, enabled with the `emotion` option. :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the entity, enabled with the `sentiment` option. :attr DisambiguationResult disambiguation: (optional) Disambiguation information for the entity. """ def __init__(self, type=None, text=None, relevance=None, mentions=None, count=None, emotion=None, sentiment=None, disambiguation=None): """ Initialize a EntitiesResult object. :param str type: (optional) Entity type. :param str text: (optional) The name of the entity. :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. :param list[EntityMention] mentions: (optional) Entity mentions and locations. :param int count: (optional) How many times the entity was mentioned in the text. :param EmotionScores emotion: (optional) Emotion analysis results for the entity, enabled with the `emotion` option. :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the entity, enabled with the `sentiment` option. :param DisambiguationResult disambiguation: (optional) Disambiguation information for the entity. """ self.type = type self.text = text self.relevance = relevance self.mentions = mentions self.count = count self.emotion = emotion self.sentiment = sentiment self.disambiguation = disambiguation @classmethod def _from_dict(cls, _dict): """Initialize a EntitiesResult object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: args['text'] = _dict.get('text') if 'relevance' in _dict: args['relevance'] = _dict.get('relevance') if 'mentions' in _dict: args['mentions'] = [ EntityMention._from_dict(x) for x in (_dict.get('mentions')) ] if 'count' in _dict: args['count'] = _dict.get('count') if 'emotion' in _dict: args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) if 'sentiment' in _dict: args['sentiment'] = FeatureSentimentResults._from_dict( _dict.get('sentiment')) if 'disambiguation' in _dict: args['disambiguation'] = DisambiguationResult._from_dict( _dict.get('disambiguation')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevance if hasattr(self, 'mentions') and self.mentions is not None: _dict['mentions'] = [x._to_dict() for x in self.mentions] if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment._to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: _dict['disambiguation'] = self.disambiguation._to_dict() return _dict def __str__(self): """Return a `str` version of this EntitiesResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EntityMention(object): """ EntityMention. :attr str text: (optional) Entity mention text. :attr list[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. """ def __init__(self, text=None, location=None): """ Initialize a EntityMention object. :param str text: (optional) Entity mention text. :param list[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. """ self.text = text self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a EntityMention object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: args['location'] = _dict.get('location') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location return _dict def __str__(self): """Return a `str` version of this EntityMention object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class FeatureSentimentResults(object): """ FeatureSentimentResults. :attr float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ def __init__(self, score=None): """ Initialize a FeatureSentimentResults object. :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ self.score = score @classmethod def _from_dict(cls, _dict): """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} if 'score' in _dict: args['score'] = _dict.get('score') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict def __str__(self): """Return a `str` version of this FeatureSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Features(object): """ Analysis features and options. :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. :attr EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. :attr EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. See [Entity types and subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding/entity-types.html). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. :attr KeywordsOptions keywords: (optional) Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. :attr MetadataOptions metadata: (optional) Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. :attr RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation types](https://cloud.ibm.com/docs/services/natural-language-understanding/relations.html). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. :attr SemanticRolesOptions semantic_roles: (optional) Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. :attr SentimentOptions sentiment: (optional) Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of the content. The top three categories are returned. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. """ def __init__(self, concepts=None, emotion=None, entities=None, keywords=None, metadata=None, relations=None, semantic_roles=None, sentiment=None, categories=None): """ Initialize a Features object. :param ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. :param EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. See [Entity types and subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding/entity-types.html). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. :param KeywordsOptions keywords: (optional) Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. :param MetadataOptions metadata: (optional) Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation types](https://cloud.ibm.com/docs/services/natural-language-understanding/relations.html). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. :param SemanticRolesOptions semantic_roles: (optional) Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. :param SentimentOptions sentiment: (optional) Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. :param CategoriesOptions categories: (optional) Returns a five-level taxonomy of the content. The top three categories are returned. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. """ self.concepts = concepts self.emotion = emotion self.entities = entities self.keywords = keywords self.metadata = metadata self.relations = relations self.semantic_roles = semantic_roles self.sentiment = sentiment self.categories = categories @classmethod def _from_dict(cls, _dict): """Initialize a Features object from a json dictionary.""" args = {} if 'concepts' in _dict: args['concepts'] = ConceptsOptions._from_dict(_dict.get('concepts')) if 'emotion' in _dict: args['emotion'] = EmotionOptions._from_dict(_dict.get('emotion')) if 'entities' in _dict: args['entities'] = EntitiesOptions._from_dict(_dict.get('entities')) if 'keywords' in _dict: args['keywords'] = KeywordsOptions._from_dict(_dict.get('keywords')) if 'metadata' in _dict: args['metadata'] = MetadataOptions._from_dict(_dict.get('metadata')) if 'relations' in _dict: args['relations'] = RelationsOptions._from_dict( _dict.get('relations')) if 'semantic_roles' in _dict: args['semantic_roles'] = SemanticRolesOptions._from_dict( _dict.get('semantic_roles')) if 'sentiment' in _dict: args['sentiment'] = SentimentOptions._from_dict( _dict.get('sentiment')) if 'categories' in _dict: args['categories'] = CategoriesOptions._from_dict( _dict.get('categories')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'concepts') and self.concepts is not None: _dict['concepts'] = self.concepts._to_dict() if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = self.entities._to_dict() if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = self.keywords._to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata._to_dict() if hasattr(self, 'relations') and self.relations is not None: _dict['relations'] = self.relations._to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: _dict['semantic_roles'] = self.semantic_roles._to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment._to_dict() if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = self.categories._to_dict() return _dict def __str__(self): """Return a `str` version of this Features object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Feed(object): """ RSS or ATOM feed found on the webpage. :attr str link: (optional) URL of the RSS or ATOM feed. """ def __init__(self, link=None): """ Initialize a Feed object. :param str link: (optional) URL of the RSS or ATOM feed. """ self.link = link @classmethod def _from_dict(cls, _dict): """Initialize a Feed object from a json dictionary.""" args = {} if 'link' in _dict: args['link'] = _dict.get('link') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'link') and self.link is not None: _dict['link'] = self.link return _dict def __str__(self): """Return a `str` version of this Feed object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class KeywordsOptions(object): """ Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. :attr int limit: (optional) Maximum number of keywords to return. :attr bool sentiment: (optional) Set this to `true` to return sentiment information for detected keywords. :attr bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ def __init__(self, limit=None, sentiment=None, emotion=None): """ Initialize a KeywordsOptions object. :param int limit: (optional) Maximum number of keywords to return. :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected keywords. :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ self.limit = limit self.sentiment = sentiment self.emotion = emotion @classmethod def _from_dict(cls, _dict): """Initialize a KeywordsOptions object from a json dictionary.""" args = {} if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: args['emotion'] = _dict.get('emotion') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion return _dict def __str__(self): """Return a `str` version of this KeywordsOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class KeywordsResult(object): """ The important keywords in the content, organized by relevance. :attr int count: (optional) Number of times the keyword appears in the analyzed text. :attr float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. :attr str text: (optional) The keyword text. :attr EmotionScores emotion: (optional) Emotion analysis results for the keyword, enabled with the `emotion` option. :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the keyword, enabled with the `sentiment` option. """ def __init__(self, count=None, relevance=None, text=None, emotion=None, sentiment=None): """ Initialize a KeywordsResult object. :param int count: (optional) Number of times the keyword appears in the analyzed text. :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. :param str text: (optional) The keyword text. :param EmotionScores emotion: (optional) Emotion analysis results for the keyword, enabled with the `emotion` option. :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the keyword, enabled with the `sentiment` option. """ self.count = count self.relevance = relevance self.text = text self.emotion = emotion self.sentiment = sentiment @classmethod def _from_dict(cls, _dict): """Initialize a KeywordsResult object from a json dictionary.""" args = {} if 'count' in _dict: args['count'] = _dict.get('count') if 'relevance' in _dict: args['relevance'] = _dict.get('relevance') if 'text' in _dict: args['text'] = _dict.get('text') if 'emotion' in _dict: args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) if 'sentiment' in _dict: args['sentiment'] = FeatureSentimentResults._from_dict( _dict.get('sentiment')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevance if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment._to_dict() return _dict def __str__(self): """Return a `str` version of this KeywordsResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ListModelsResults(object): """ Custom models that are available for entities and relations. :attr list[Model] models: (optional) An array of available models. """ def __init__(self, models=None): """ Initialize a ListModelsResults object. :param list[Model] models: (optional) An array of available models. """ self.models = models @classmethod def _from_dict(cls, _dict): """Initialize a ListModelsResults object from a json dictionary.""" args = {} if 'models' in _dict: args['models'] = [ Model._from_dict(x) for x in (_dict.get('models')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict def __str__(self): """Return a `str` version of this ListModelsResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetadataOptions(object): """ Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. """ def __init__(self, **kwargs): """ Initialize a MetadataOptions object. :param **kwargs: (optional) Any additional properties. """ for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a MetadataOptions object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {} if not hasattr(self, '_additionalProperties'): super(MetadataOptions, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(MetadataOptions, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this MetadataOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MetadataResult(object): """ The authors, publication date, title, prominent page image, and RSS/ATOM feeds of the webpage. Supports URL and HTML input types. :attr list[Author] authors: (optional) The authors of the document. :attr str publication_date: (optional) The publication date in the format ISO 8601. :attr str title: (optional) The title of the document. :attr str image: (optional) URL of a prominent image on the webpage. :attr list[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ def __init__(self, authors=None, publication_date=None, title=None, image=None, feeds=None): """ Initialize a MetadataResult object. :param list[Author] authors: (optional) The authors of the document. :param str publication_date: (optional) The publication date in the format ISO 8601. :param str title: (optional) The title of the document. :param str image: (optional) URL of a prominent image on the webpage. :param list[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ self.authors = authors self.publication_date = publication_date self.title = title self.image = image self.feeds = feeds @classmethod def _from_dict(cls, _dict): """Initialize a MetadataResult object from a json dictionary.""" args = {} if 'authors' in _dict: args['authors'] = [ Author._from_dict(x) for x in (_dict.get('authors')) ] if 'publication_date' in _dict: args['publication_date'] = _dict.get('publication_date') if 'title' in _dict: args['title'] = _dict.get('title') if 'image' in _dict: args['image'] = _dict.get('image') if 'feeds' in _dict: args['feeds'] = [Feed._from_dict(x) for x in (_dict.get('feeds'))] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'authors') and self.authors is not None: _dict['authors'] = [x._to_dict() for x in self.authors] if hasattr(self, 'publication_date') and self.publication_date is not None: _dict['publication_date'] = self.publication_date if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'image') and self.image is not None: _dict['image'] = self.image if hasattr(self, 'feeds') and self.feeds is not None: _dict['feeds'] = [x._to_dict() for x in self.feeds] return _dict def __str__(self): """Return a `str` version of this MetadataResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Model(object): """ 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 model. :attr str description: (optional) Model description. :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :attr str version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. :attr str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :attr datetime created: (optional) A dateTime indicating when the model was created. """ def __init__(self, status=None, model_id=None, language=None, description=None, workspace_id=None, version=None, version_description=None, created=None): """ Initialize a Model object. :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 description: (optional) Model description. :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :param str version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :param datetime created: (optional) A dateTime indicating when the model was created. """ self.status = status self.model_id = model_id self.language = language self.description = description self.workspace_id = workspace_id self.version = version self.version_description = version_description self.created = created @classmethod def _from_dict(cls, _dict): """Initialize a Model object from a json dictionary.""" args = {} if 'status' in _dict: args['status'] = _dict.get('status') if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'language' in _dict: args['language'] = _dict.get('language') if 'description' in _dict: args['description'] = _dict.get('description') if 'workspace_id' in _dict: args['workspace_id'] = _dict.get('workspace_id') if 'version' in _dict: args['version'] = _dict.get('version') if 'version_description' in _dict: args['version_description'] = _dict.get('version_description') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'workspace_id') and self.workspace_id is not None: _dict['workspace_id'] = self.workspace_id if hasattr(self, 'version') and self.version is not None: _dict['version'] = self.version if hasattr( self, 'version_description') and self.version_description is not None: _dict['version_description'] = self.version_description if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) return _dict def __str__(self): """Return a `str` version of this Model object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RelationArgument(object): """ RelationArgument. :attr list[RelationEntity] entities: (optional) An array of extracted entities. :attr list[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :attr str text: (optional) Text that corresponds to the argument. """ def __init__(self, entities=None, location=None, text=None): """ Initialize a RelationArgument object. :param list[RelationEntity] entities: (optional) An array of extracted entities. :param list[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :param str text: (optional) Text that corresponds to the argument. """ self.entities = entities self.location = location self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a RelationArgument object from a json dictionary.""" args = {} if 'entities' in _dict: args['entities'] = [ RelationEntity._from_dict(x) for x in (_dict.get('entities')) ] if 'location' in _dict: args['location'] = _dict.get('location') if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this RelationArgument object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RelationEntity(object): """ An entity that corresponds with an argument in a relation. :attr str text: (optional) Text that corresponds to the entity. :attr str type: (optional) Entity type. """ def __init__(self, text=None, type=None): """ Initialize a RelationEntity object. :param str text: (optional) Text that corresponds to the entity. :param str type: (optional) Entity type. """ self.text = text self.type = type @classmethod def _from_dict(cls, _dict): """Initialize a RelationEntity object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'type' in _dict: args['type'] = _dict.get('type') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type return _dict def __str__(self): """Return a `str` version of this RelationEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RelationsOptions(object): """ Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation types](https://cloud.ibm.com/docs/services/natural-language-understanding/relations.html). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. :attr str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) ID to override the default model. """ def __init__(self, model=None): """ Initialize a RelationsOptions object. :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) ID to override the default model. """ self.model = model @classmethod def _from_dict(cls, _dict): """Initialize a RelationsOptions object from a json dictionary.""" args = {} if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'model') and self.model is not None: _dict['model'] = self.model return _dict def __str__(self): """Return a `str` version of this RelationsOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RelationsResult(object): """ The relations between entities found in the content. :attr float score: (optional) Confidence score for the relation. Higher values indicate greater confidence. :attr str sentence: (optional) The sentence that contains the relation. :attr str type: (optional) The type of the relation. :attr list[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ def __init__(self, score=None, sentence=None, type=None, arguments=None): """ Initialize a RelationsResult object. :param float score: (optional) Confidence score for the relation. Higher values indicate greater confidence. :param str sentence: (optional) The sentence that contains the relation. :param str type: (optional) The type of the relation. :param list[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ self.score = score self.sentence = sentence self.type = type self.arguments = arguments @classmethod def _from_dict(cls, _dict): """Initialize a RelationsResult object from a json dictionary.""" args = {} if 'score' in _dict: args['score'] = _dict.get('score') if 'sentence' in _dict: args['sentence'] = _dict.get('sentence') if 'type' in _dict: args['type'] = _dict.get('type') if 'arguments' in _dict: args['arguments'] = [ RelationArgument._from_dict(x) for x in (_dict.get('arguments')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'arguments') and self.arguments is not None: _dict['arguments'] = [x._to_dict() for x in self.arguments] return _dict def __str__(self): """Return a `str` version of this RelationsResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesAction(object): """ SemanticRolesAction. :attr str text: (optional) Analyzed text that corresponds to the action. :attr str normalized: (optional) normalized version of the action. :attr SemanticRolesVerb verb: (optional) """ def __init__(self, text=None, normalized=None, verb=None): """ Initialize a SemanticRolesAction object. :param str text: (optional) Analyzed text that corresponds to the action. :param str normalized: (optional) normalized version of the action. :param SemanticRolesVerb verb: (optional) """ self.text = text self.normalized = normalized self.verb = verb @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesAction object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'normalized' in _dict: args['normalized'] = _dict.get('normalized') if 'verb' in _dict: args['verb'] = SemanticRolesVerb._from_dict(_dict.get('verb')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'normalized') and self.normalized is not None: _dict['normalized'] = self.normalized if hasattr(self, 'verb') and self.verb is not None: _dict['verb'] = self.verb._to_dict() return _dict def __str__(self): """Return a `str` version of this SemanticRolesAction object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesEntity(object): """ SemanticRolesEntity. :attr str type: (optional) Entity type. :attr str text: (optional) The entity text. """ def __init__(self, type=None, text=None): """ Initialize a SemanticRolesEntity object. :param str type: (optional) Entity type. :param str text: (optional) The entity text. """ self.type = type self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this SemanticRolesEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesKeyword(object): """ SemanticRolesKeyword. :attr str text: (optional) The keyword text. """ def __init__(self, text=None): """ Initialize a SemanticRolesKeyword object. :param str text: (optional) The keyword text. """ self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this SemanticRolesKeyword object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesObject(object): """ SemanticRolesObject. :attr str text: (optional) Object text. :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ def __init__(self, text=None, keywords=None): """ Initialize a SemanticRolesObject object. :param str text: (optional) Object text. :param list[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ self.text = text self.keywords = keywords @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesObject object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'keywords' in _dict: args['keywords'] = [ SemanticRolesKeyword._from_dict(x) for x in (_dict.get('keywords')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = [x._to_dict() for x in self.keywords] return _dict def __str__(self): """Return a `str` version of this SemanticRolesObject object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesOptions(object): """ Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. :attr int limit: (optional) Maximum number of semantic_roles results to return. :attr bool keywords: (optional) Set this to `true` to return keyword information for subjects and objects. :attr bool entities: (optional) Set this to `true` to return entity information for subjects and objects. """ def __init__(self, limit=None, keywords=None, entities=None): """ Initialize a SemanticRolesOptions object. :param int limit: (optional) Maximum number of semantic_roles results to return. :param bool keywords: (optional) Set this to `true` to return keyword information for subjects and objects. :param bool entities: (optional) Set this to `true` to return entity information for subjects and objects. """ self.limit = limit self.keywords = keywords self.entities = entities @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'keywords' in _dict: args['keywords'] = _dict.get('keywords') if 'entities' in _dict: args['entities'] = _dict.get('entities') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = self.keywords if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = self.entities return _dict def __str__(self): """Return a `str` version of this SemanticRolesOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesResult(object): """ The object containing the actions and the objects the actions act upon. :attr str sentence: (optional) Sentence from the source that contains the subject, action, and object. :attr SemanticRolesSubject subject: (optional) The extracted subject from the sentence. :attr SemanticRolesAction action: (optional) The extracted action from the sentence. :attr SemanticRolesObject object: (optional) The extracted object from the sentence. """ def __init__(self, sentence=None, subject=None, action=None, object=None): """ Initialize a SemanticRolesResult object. :param str sentence: (optional) Sentence from the source that contains the subject, action, and object. :param SemanticRolesSubject subject: (optional) The extracted subject from the sentence. :param SemanticRolesAction action: (optional) The extracted action from the sentence. :param SemanticRolesObject object: (optional) The extracted object from the sentence. """ self.sentence = sentence self.subject = subject self.action = action self.object = object @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} if 'sentence' in _dict: args['sentence'] = _dict.get('sentence') if 'subject' in _dict: args['subject'] = SemanticRolesSubject._from_dict( _dict.get('subject')) if 'action' in _dict: args['action'] = SemanticRolesAction._from_dict(_dict.get('action')) if 'object' in _dict: args['object'] = SemanticRolesObject._from_dict(_dict.get('object')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: _dict['subject'] = self.subject._to_dict() if hasattr(self, 'action') and self.action is not None: _dict['action'] = self.action._to_dict() if hasattr(self, 'object') and self.object is not None: _dict['object'] = self.object._to_dict() return _dict def __str__(self): """Return a `str` version of this SemanticRolesResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesSubject(object): """ SemanticRolesSubject. :attr str text: (optional) Text that corresponds to the subject role. :attr list[SemanticRolesEntity] entities: (optional) An array of extracted entities. :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ def __init__(self, text=None, entities=None, keywords=None): """ Initialize a SemanticRolesSubject object. :param str text: (optional) Text that corresponds to the subject role. :param list[SemanticRolesEntity] entities: (optional) An array of extracted entities. :param list[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ self.text = text self.entities = entities self.keywords = keywords @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesSubject object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'entities' in _dict: args['entities'] = [ SemanticRolesEntity._from_dict(x) for x in (_dict.get('entities')) ] if 'keywords' in _dict: args['keywords'] = [ SemanticRolesKeyword._from_dict(x) for x in (_dict.get('keywords')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = [x._to_dict() for x in self.keywords] return _dict def __str__(self): """Return a `str` version of this SemanticRolesSubject object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SemanticRolesVerb(object): """ SemanticRolesVerb. :attr str text: (optional) The keyword text. :attr str tense: (optional) Verb tense. """ def __init__(self, text=None, tense=None): """ Initialize a SemanticRolesVerb object. :param str text: (optional) The keyword text. :param str tense: (optional) Verb tense. """ self.text = text self.tense = tense @classmethod def _from_dict(cls, _dict): """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'tense' in _dict: args['tense'] = _dict.get('tense') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'tense') and self.tense is not None: _dict['tense'] = self.tense return _dict def __str__(self): """Return a `str` version of this SemanticRolesVerb object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SentimentOptions(object): """ Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. :attr bool document: (optional) Set this to `false` to hide document-level sentiment results. :attr list[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ def __init__(self, document=None, targets=None): """ Initialize a SentimentOptions object. :param bool document: (optional) Set this to `false` to hide document-level sentiment results. :param list[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ self.document = document self.targets = targets @classmethod def _from_dict(cls, _dict): """Initialize a SentimentOptions object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: args['targets'] = _dict.get('targets') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets return _dict def __str__(self): """Return a `str` version of this SentimentOptions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SentimentResult(object): """ The sentiment of the content. :attr DocumentSentimentResults document: (optional) The document level sentiment. :attr list[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ def __init__(self, document=None, targets=None): """ Initialize a SentimentResult object. :param DocumentSentimentResults document: (optional) The document level sentiment. :param list[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ self.document = document self.targets = targets @classmethod def _from_dict(cls, _dict): """Initialize a SentimentResult object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = DocumentSentimentResults._from_dict( _dict.get('document')) if 'targets' in _dict: args['targets'] = [ TargetedSentimentResults._from_dict(x) for x in (_dict.get('targets')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document._to_dict() if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = [x._to_dict() for x in self.targets] return _dict def __str__(self): """Return a `str` version of this SentimentResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TargetedEmotionResults(object): """ Emotion results for a specified target. :attr str text: (optional) Targeted text. :attr EmotionScores emotion: (optional) The emotion results for the target. """ def __init__(self, text=None, emotion=None): """ Initialize a TargetedEmotionResults object. :param str text: (optional) Targeted text. :param EmotionScores emotion: (optional) The emotion results for the target. """ self.text = text self.emotion = emotion @classmethod def _from_dict(cls, _dict): """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'emotion' in _dict: args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() return _dict def __str__(self): """Return a `str` version of this TargetedEmotionResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TargetedSentimentResults(object): """ TargetedSentimentResults. :attr str text: (optional) Targeted text. :attr float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ def __init__(self, text=None, score=None): """ Initialize a TargetedSentimentResults object. :param str text: (optional) Targeted text. :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ self.text = text self.score = score @classmethod def _from_dict(cls, _dict): """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') if 'score' in _dict: args['score'] = _dict.get('score') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict def __str__(self): """Return a `str` version of this TargetedSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Usage(object): """ Usage information. :attr int features: (optional) Number of features used in the API call. :attr int text_characters: (optional) Number of text characters processed. :attr int text_units: (optional) Number of 10,000-character units processed. """ def __init__(self, features=None, text_characters=None, text_units=None): """ Initialize a Usage object. :param int features: (optional) Number of features used in the API call. :param int text_characters: (optional) Number of text characters processed. :param int text_units: (optional) Number of 10,000-character units processed. """ self.features = features self.text_characters = text_characters self.text_units = text_units @classmethod def _from_dict(cls, _dict): """Initialize a Usage object from a json dictionary.""" args = {} if 'features' in _dict: args['features'] = _dict.get('features') if 'text_characters' in _dict: args['text_characters'] = _dict.get('text_characters') if 'text_units' in _dict: args['text_units'] = _dict.get('text_units') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'features') and self.features is not None: _dict['features'] = self.features if hasattr(self, 'text_characters') and self.text_characters is not None: _dict['text_characters'] = self.text_characters if hasattr(self, 'text_units') and self.text_units is not None: _dict['text_units'] = self.text_units return _dict def __str__(self): """Return a `str` version of this Usage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/text_to_speech_v1.py0000644000076500000240000021415513451407070030415 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ ### Service Overview The IBM® 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. For speech synthesis, the service supports a synchronous HTTP Representational State Transfer (REST) interface. It also supports a WebSocket interface that provides both plain text and SSML input, including the SSML <mark> element and word timings. SSML is an XML-based markup language that provides text annotation for speech-synthesis applications. The service also offers a customization interface. You can use the interface to define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more words that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic Phonetic Representation (SPR). """ from __future__ import absolute_import import json from .watson_service import WatsonService ############################################################################## # Service ############################################################################## class TextToSpeechV1(WatsonService): """The Text to Speech V1 service.""" default_url = 'https://stream.watsonplatform.net/text-to-speech/api' def __init__( self, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Text to Speech service. :param str url: The base url to use when contacting the service (e.g. "https://stream.watsonplatform.net/text-to-speech/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='text_to_speech', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Text to Speech') ######################### # Voices ######################### def get_voice(self, voice, customization_id=None, **kwargs): """ Get a voice. Gets information about the specified voice. The information includes the name, language, gender, and other details about the voice. Specify a customization ID to obtain information for that custom voice model of the specified voice. To list information about all available voices, use the **List voices** method. **See also:** [Specifying a voice](https://cloud.ibm.com/docs/services/text-to-speech/http.html#voices). :param str voice: The voice for which information is to be returned. :param str customization_id: The customization ID (GUID) of a custom voice model for which information is to be returned. You must make the request with service credentials created for the instance of the service that owns the custom model. Omit the parameter to see information about the specified voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if voice is None: raise ValueError('voice must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=get_voice' params = {'customization_id': customization_id} url = '/v1/voices/{0}'.format(*self._encode_path_vars(voice)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_voices(self, **kwargs): """ 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. **See also:** [Specifying a voice](https://cloud.ibm.com/docs/services/text-to-speech/http.html#voices). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=list_voices' url = '/v1/voices' response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response ######################### # Synthesis ######################### def synthesize(self, text, accept=None, voice=None, customization_id=None, **kwargs): """ Synthesize audio. Synthesizes text to audio that is spoken in the specified voice. The service bases its understanding of the language for the input text on the specified voice. Use a voice that matches the language of the input text. The service returns the synthesized audio stream as an array of bytes. You can pass a maximum of 5 KB of text to the service. **See also:** [Synthesizing text to audio](https://cloud.ibm.com/docs/services/text-to-speech/http.html#synthesize). ### Audio formats (accept types) The service can return audio in the following formats (MIME types). * Where indicated, you can optionally specify the sampling rate (`rate`) of the audio. You must specify a sampling rate for the `audio/l16` and `audio/mulaw` formats. A specified sampling rate must lie in the range of 8 kHz to 192 kHz. * For the `audio/l16` format, you can optionally specify the endianness (`endianness`) of the audio: `endianness=big-endian` or `endianness=little-endian`. Use the `Accept` header or the `accept` parameter to specify the requested format of the response audio. If you omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec (`audio/ogg;codecs=opus`). The service always returns single-channel audio. * `audio/basic` The service returns audio with a sampling rate of 8000 Hz. * `audio/flac` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. * `audio/l16` You must specify the `rate` of the audio. You can optionally specify the `endianness` of the audio. The default endianness is `little-endian`. * `audio/mp3` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. * `audio/mpeg` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. * `audio/mulaw` You must specify the `rate` of the audio. * `audio/ogg` The service returns the audio in the `vorbis` codec. You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. * `audio/ogg;codecs=opus` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. * `audio/ogg;codecs=vorbis` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. * `audio/wav` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. * `audio/webm` The service returns the audio in the `opus` codec. The service returns audio with a sampling rate of 48,000 Hz. * `audio/webm;codecs=opus` The service returns audio with a sampling rate of 48,000 Hz. * `audio/webm;codecs=vorbis` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. For more information about specifying an audio format, including additional details about some of the formats, see [Specifying an audio format](https://cloud.ibm.com/docs/services/text-to-speech/http.html#format). ### Warning messages If a request includes invalid query parameters, the service returns a `Warnings` response header that provides messages about the invalid parameters. The warning includes a descriptive message and a list of invalid argument strings. For example, a message such as `\"Unknown arguments:\"` or `\"Unknown url query arguments:\"` followed by a list of the form `\"{invalid_arg_1}, {invalid_arg_2}.\"` The request succeeds despite the warnings. :param str text: The text to synthesize. :param str accept: The requested format (MIME type) of the audio. You can use the `Accept` header or the `accept` parameter to specify the audio format. For more information about specifying an audio format, see **Audio formats (accept types)** in the method description. Default: `audio/ogg;codecs=opus`. :param str voice: The voice to use for synthesis. :param str customization_id: The customization ID (GUID) of a custom voice model to use for the synthesis. If a custom voice model is specified, it is guaranteed to work only if it matches the language of the indicated voice. You must make the request with service credentials created for the instance of the service that owns the custom model. Omit the parameter to use the specified voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if text is None: raise ValueError('text must be provided') headers = {'Accept': accept} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=synthesize' params = {'voice': voice, 'customization_id': customization_id} data = {'text': text} url = '/v1/synthesize' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=False) return response ######################### # Pronunciation ######################### def get_pronunciation(self, text, voice=None, format=None, customization_id=None, **kwargs): """ Get pronunciation. Gets the phonetic pronunciation for the specified word. You can request the pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom voice model to see the translation for that voice model. **Note:** This method is currently a beta release. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuWordsQueryLanguage). :param str text: The word for which the pronunciation is requested. :param str voice: A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for example, `en-US`) return the same translation. :param str format: The phoneme format in which to return the pronunciation. Omit the parameter to obtain the pronunciation in the default format. :param str customization_id: The customization ID (GUID) of a custom voice model for which the pronunciation is to be returned. The language of a specified custom model must match the language of the specified voice. If the word is not defined in the specified custom model, the service returns the default translation for the custom model's language. You must make the request with service credentials created for the instance of the service that owns the custom model. Omit the parameter to see the translation for the specified voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=get_pronunciation' params = { 'text': text, 'voice': voice, 'format': format, 'customization_id': customization_id } url = '/v1/pronunciation' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Custom models ######################### def create_voice_model(self, name, language=None, description=None, **kwargs): """ Create a custom model. Creates a new empty custom voice model. You must specify a name for the new custom model. You can optionally specify the language and a description for the new model. The model is owned by the instance of the service whose credentials are used to create it. **Note:** This method is currently a beta release. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-models.html#cuModelsCreate). :param str name: The name of the new custom voice model. :param str language: The language of the new custom voice model. Omit the parameter to use the the default language, `en-US`. :param str description: A description of the new custom voice model. Specifying a description is recommended. :param 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') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=create_voice_model' data = {'name': name, 'language': language, 'description': description} url = '/v1/customizations' response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response def delete_voice_model(self, customization_id, **kwargs): """ Delete a custom model. Deletes the specified custom voice model. You must use credentials for the instance of the service that owns a model to delete it. **Note:** This method is currently a beta release. **See also:** [Deleting a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-models.html#cuModelsDelete). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=delete_voice_model' url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_voice_model(self, customization_id, **kwargs): """ Get a custom model. Gets all information about a specified custom voice model. In addition to metadata such as the name and description of the voice model, the output includes the words and their translations as defined in the model. To see just the metadata for a voice model, use the **List custom models** method. **Note:** This method is currently a beta release. **See also:** [Querying a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-models.html#cuModelsQuery). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=get_voice_model' url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_voice_models(self, language=None, **kwargs): """ List custom models. Lists metadata such as the name and description for all custom voice models that are owned by an instance of the service. Specify a language to list the voice models for that language only. To see the words in addition to the metadata for a specific voice model, use the **List a custom model** method. You must use credentials for the instance of the service that owns a model to list information about it. **Note:** This method is currently a beta release. **See also:** [Querying all custom models](https://cloud.ibm.com/docs/services/text-to-speech/custom-models.html#cuModelsQueryAll). :param str language: The language for which custom voice models that are owned by the requesting service credentials are to be returned. Omit the parameter to see all custom voice models that are owned by the requester. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=list_voice_models' params = {'language': language} url = '/v1/customizations' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_voice_model(self, customization_id, name=None, description=None, words=None, **kwargs): """ Update a custom model. Updates information for the specified custom voice model. You can update metadata such as the name and description of the voice model. You can also update the words in the model and their translations. Adding a new translation for a word that already exists in a custom model overwrites the word's existing translation. A custom model can contain no more than 20,000 entries. You must use credentials for the instance of the service that owns a model to update it. You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation <phoneme alphabet=\"ipa\" ph=\"təmˈɑto\"></phoneme> or in the proprietary IBM Symbolic Phonetic Representation (SPR) <phoneme alphabet=\"ibm\" ph=\"1gAstroEntxrYFXs\"></phoneme> **Note:** This method is currently a beta release. **See also:** * [Updating a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-models.html#cuModelsUpdate) * [Adding words to a Japanese custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuJapaneseAdd) * [Understanding customization](https://cloud.ibm.com/docs/services/text-to-speech/custom-intro.html). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param str name: A new name for the custom voice model. :param str description: A new description for the custom voice model. :param list[Word] words: An array of `Word` objects that provides the words and their translations that are to be added or updated for the custom voice model. Pass an empty array to make no additions or updates. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if words is not None: words = [self._convert_model(x, Word) for x in words] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=update_voice_model' data = {'name': name, 'description': description, 'words': words} url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response ######################### # Custom words ######################### def add_word(self, customization_id, word, translation, part_of_speech=None, **kwargs): """ Add a custom word. Adds a single word and its translation to the specified custom voice model. Adding a new translation for a word that already exists in a custom model overwrites the word's existing translation. A custom model can contain no more than 20,000 entries. You must use credentials for the instance of the service that owns a model to add a word to it. You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation <phoneme alphabet=\"ipa\" ph=\"təmˈɑto\"></phoneme> or in the proprietary IBM Symbolic Phonetic Representation (SPR) <phoneme alphabet=\"ibm\" ph=\"1gAstroEntxrYFXs\"></phoneme> **Note:** This method is currently a beta release. **See also:** * [Adding a single word to a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuWordAdd) * [Adding words to a Japanese custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuJapaneseAdd) * [Understanding customization](https://cloud.ibm.com/docs/services/text-to-speech/custom-intro.html). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param str word: The word that is to be added or updated for the custom voice model. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR translation. A sounds-like is one or more words that, when combined, sound like the word. :param str part_of_speech: **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese entries](https://cloud.ibm.com/docs/services/text-to-speech/custom-rules.html#jaNotes). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if word is None: raise ValueError('word must be provided') if translation is None: raise ValueError('translation must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=add_word' data = {'translation': translation, 'part_of_speech': part_of_speech} url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) response = self.request( method='PUT', url=url, headers=headers, json=data, accept_json=True) return response def add_words(self, customization_id, words, **kwargs): """ Add custom words. Adds one or more words and their translations to the specified custom voice model. Adding a new translation for a word that already exists in a custom model overwrites the word's existing translation. A custom model can contain no more than 20,000 entries. You must use credentials for the instance of the service that owns a model to add words to it. You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation <phoneme alphabet=\"ipa\" ph=\"təmˈɑto\"></phoneme> or in the proprietary IBM Symbolic Phonetic Representation (SPR) <phoneme alphabet=\"ibm\" ph=\"1gAstroEntxrYFXs\"></phoneme> **Note:** This method is currently a beta release. **See also:** * [Adding multiple words to a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuWordsAdd) * [Adding words to a Japanese custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuJapaneseAdd) * [Understanding customization](https://cloud.ibm.com/docs/services/text-to-speech/custom-intro.html). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param list[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each object shows a word and its translation from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') words = [self._convert_model(x, Word) for x in words] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=add_words' data = {'words': words} url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) response = self.request( method='POST', url=url, headers=headers, json=data, accept_json=True) return response def delete_word(self, customization_id, word, **kwargs): """ Delete a custom word. Deletes a single word from the specified custom voice model. You must use credentials for the instance of the service that owns a model to delete its words. **Note:** This method is currently a beta release. **See also:** [Deleting a word from a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuWordDelete). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param str word: The word that is to be deleted from the custom voice model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if word is None: raise ValueError('word must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=delete_word' url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) response = self.request( method='DELETE', url=url, headers=headers, accept_json=True) return response def get_word(self, customization_id, word, **kwargs): """ Get a custom word. Gets the translation for a single word from the specified custom model. The output shows the translation as it is defined in the model. You must use credentials for the instance of the service that owns a model to list its words. **Note:** This method is currently a beta release. **See also:** [Querying a single word from a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuWordQueryModel). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param str word: The word that is to be queried from the custom voice model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') if word is None: raise ValueError('word must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=get_word' url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response def list_words(self, customization_id, **kwargs): """ List custom words. Lists all of the words and their translations for the specified custom voice model. The output shows the translations as they are defined in the model. You must use credentials for the instance of the service that owns a model to list its words. **Note:** This method is currently a beta release. **See also:** [Querying all words from a custom model](https://cloud.ibm.com/docs/services/text-to-speech/custom-entries.html#cuWordsQueryModel). :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with service credentials created for the instance of the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if customization_id is None: raise ValueError('customization_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=list_words' url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) response = self.request( method='GET', url=url, headers=headers, accept_json=True) return response ######################### # User data ######################### def delete_user_data(self, customer_id, **kwargs): """ Delete labeled data. Deletes all data that is associated with a specified customer ID. The method 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. **See also:** [Information security](https://cloud.ibm.com/docs/services/text-to-speech/information-security.html). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=text_to_speech;service_version=V1;operation_id=delete_user_data' params = {'customer_id': customer_id} url = '/v1/user_data' response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class Pronunciation(object): """ Pronunciation. :attr str pronunciation: The pronunciation of the specified text in the requested voice and format. If a custom voice model is specified, the pronunciation also reflects that custom voice. """ def __init__(self, pronunciation): """ Initialize a Pronunciation object. :param str pronunciation: The pronunciation of the specified text in the requested voice and format. If a custom voice model is specified, the pronunciation also reflects that custom voice. """ self.pronunciation = pronunciation @classmethod def _from_dict(cls, _dict): """Initialize a Pronunciation object from a json dictionary.""" args = {} if 'pronunciation' in _dict: args['pronunciation'] = _dict.get('pronunciation') else: raise ValueError( 'Required property \'pronunciation\' not present in Pronunciation JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pronunciation') and self.pronunciation is not None: _dict['pronunciation'] = self.pronunciation return _dict def __str__(self): """Return a `str` version of this Pronunciation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SupportedFeatures(object): """ Describes the additional service features that are supported with the voice. :attr bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). :attr bool voice_transformation: If `true`, the voice can be transformed by using the SSML <voice-transformation> element; if `false`, the voice cannot be transformed. """ def __init__(self, custom_pronunciation, voice_transformation): """ Initialize a SupportedFeatures object. :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). :param bool voice_transformation: If `true`, the voice can be transformed by using the SSML <voice-transformation> element; if `false`, the voice cannot be transformed. """ self.custom_pronunciation = custom_pronunciation self.voice_transformation = voice_transformation @classmethod def _from_dict(cls, _dict): """Initialize a SupportedFeatures object from a json dictionary.""" args = {} if 'custom_pronunciation' in _dict: args['custom_pronunciation'] = _dict.get('custom_pronunciation') else: raise ValueError( 'Required property \'custom_pronunciation\' not present in SupportedFeatures JSON' ) if 'voice_transformation' in _dict: args['voice_transformation'] = _dict.get('voice_transformation') else: raise ValueError( 'Required property \'voice_transformation\' not present in SupportedFeatures JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'custom_pronunciation' ) and self.custom_pronunciation is not None: _dict['custom_pronunciation'] = self.custom_pronunciation if hasattr(self, 'voice_transformation' ) and self.voice_transformation is not None: _dict['voice_transformation'] = self.voice_transformation return _dict def __str__(self): """Return a `str` version of this SupportedFeatures object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Translation(object): """ Translation. :attr str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR translation. A sounds-like is one or more words that, when combined, sound like the word. :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese entries](https://cloud.ibm.com/docs/services/text-to-speech/custom-rules.html#jaNotes). """ def __init__(self, translation, part_of_speech=None): """ Initialize a Translation object. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR translation. A sounds-like is one or more words that, when combined, sound like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese entries](https://cloud.ibm.com/docs/services/text-to-speech/custom-rules.html#jaNotes). """ self.translation = translation self.part_of_speech = part_of_speech @classmethod def _from_dict(cls, _dict): """Initialize a Translation object from a json dictionary.""" args = {} if 'translation' in _dict: args['translation'] = _dict.get('translation') else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' ) if 'part_of_speech' in _dict: args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'translation') and self.translation is not None: _dict['translation'] = self.translation if hasattr(self, 'part_of_speech') and self.part_of_speech is not None: _dict['part_of_speech'] = self.part_of_speech return _dict def __str__(self): """Return a `str` version of this Translation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Voice(object): """ Voice. :attr str url: The URI of the voice. :attr str gender: The gender of the voice: `male` or `female`. :attr str name: The name of the voice. Use this as the voice identifier in all requests. :attr str language: The language and region of the voice (for example, `en-US`). :attr str description: A textual description of the voice. :attr bool customizable: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `custom_pronunciation`; maintained for backward compatibility.). :attr SupportedFeatures supported_features: Describes the additional service features that are supported with the voice. :attr VoiceModel customization: (optional) Returns information about a specified custom voice model. This field is returned only by the **Get a voice** method and only when you specify the customization ID of a custom voice model. """ def __init__(self, url, gender, name, language, description, customizable, supported_features, customization=None): """ Initialize a Voice object. :param str url: The URI of the voice. :param str gender: The gender of the voice: `male` or `female`. :param str name: The name of the voice. Use this as the voice identifier in all requests. :param str language: The language and region of the voice (for example, `en-US`). :param str description: A textual description of the voice. :param bool customizable: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `custom_pronunciation`; maintained for backward compatibility.). :param SupportedFeatures supported_features: Describes the additional service features that are supported with the voice. :param VoiceModel customization: (optional) Returns information about a specified custom voice model. This field is returned only by the **Get a voice** method and only when you specify the customization ID of a custom voice model. """ self.url = url self.gender = gender self.name = name self.language = language self.description = description self.customizable = customizable self.supported_features = supported_features self.customization = customization @classmethod def _from_dict(cls, _dict): """Initialize a Voice object from a json dictionary.""" args = {} if 'url' in _dict: args['url'] = _dict.get('url') else: raise ValueError( 'Required property \'url\' not present in Voice JSON') if 'gender' in _dict: args['gender'] = _dict.get('gender') else: raise ValueError( 'Required property \'gender\' not present in Voice JSON') if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Voice JSON') if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in Voice JSON') if 'description' in _dict: args['description'] = _dict.get('description') else: raise ValueError( 'Required property \'description\' not present in Voice JSON') if 'customizable' in _dict: args['customizable'] = _dict.get('customizable') else: raise ValueError( 'Required property \'customizable\' not present in Voice JSON') if 'supported_features' in _dict: args['supported_features'] = SupportedFeatures._from_dict( _dict.get('supported_features')) else: raise ValueError( 'Required property \'supported_features\' not present in Voice JSON' ) if 'customization' in _dict: args['customization'] = VoiceModel._from_dict( _dict.get('customization')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'gender') and self.gender is not None: _dict['gender'] = self.gender if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'customizable') and self.customizable is not None: _dict['customizable'] = self.customizable if hasattr( self, 'supported_features') and self.supported_features is not None: _dict['supported_features'] = self.supported_features._to_dict() if hasattr(self, 'customization') and self.customization is not None: _dict['customization'] = self.customization._to_dict() return _dict def __str__(self): """Return a `str` version of this Voice object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class VoiceModel(object): """ VoiceModel. :attr str customization_id: The customization ID (GUID) of the custom voice model. The **Create a custom model** method returns only this field. It does not not return the other fields of this object. :attr str name: (optional) The name of the custom voice model. :attr str language: (optional) The language identifier of the custom voice model (for example, `en-US`). :attr str owner: (optional) The GUID of the service credentials for the instance of the service that owns the custom voice model. :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom voice model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :attr str last_modified: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom voice model was last modified. Equals `created` when a new voice model is first added but has yet to be updated. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :attr str description: (optional) The description of the custom voice model. :attr list[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no words. This field is returned only by the **Get a voice** method and only when you specify the customization ID of a custom voice model. """ def __init__(self, customization_id, name=None, language=None, owner=None, created=None, last_modified=None, description=None, words=None): """ Initialize a VoiceModel object. :param str customization_id: The customization ID (GUID) of the custom voice model. The **Create a custom model** method returns only this field. It does not not return the other fields of this object. :param str name: (optional) The name of the custom voice model. :param str language: (optional) The language identifier of the custom voice model (for example, `en-US`). :param str owner: (optional) The GUID of the service credentials for the instance of the service that owns the custom voice model. :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom voice model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :param str last_modified: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom voice model was last modified. Equals `created` when a new voice model is first added but has yet to be updated. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :param str description: (optional) The description of the custom voice model. :param list[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no words. This field is returned only by the **Get a voice** method and only when you specify the customization ID of a custom voice model. """ self.customization_id = customization_id self.name = name self.language = language self.owner = owner self.created = created self.last_modified = last_modified self.description = description self.words = words @classmethod def _from_dict(cls, _dict): """Initialize a VoiceModel object from a json dictionary.""" args = {} if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: raise ValueError( 'Required property \'customization_id\' not present in VoiceModel JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') if 'language' in _dict: args['language'] = _dict.get('language') if 'owner' in _dict: args['owner'] = _dict.get('owner') if 'created' in _dict: args['created'] = _dict.get('created') if 'last_modified' in _dict: args['last_modified'] = _dict.get('last_modified') if 'description' in _dict: args['description'] = _dict.get('description') if 'words' in _dict: args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customization_id') and self.customization_id is not None: _dict['customization_id'] = self.customization_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'owner') and self.owner is not None: _dict['owner'] = self.owner if hasattr(self, 'created') and self.created is not None: _dict['created'] = self.created if hasattr(self, 'last_modified') and self.last_modified is not None: _dict['last_modified'] = self.last_modified if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'words') and self.words is not None: _dict['words'] = [x._to_dict() for x in self.words] return _dict def __str__(self): """Return a `str` version of this VoiceModel object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class VoiceModels(object): """ VoiceModels. :attr list[VoiceModel] customizations: An array of `VoiceModel` objects that provides information about each available custom voice model. The array is empty if the requesting service credentials own no custom voice models (if no language is specified) or own no custom voice models for the specified language. """ def __init__(self, customizations): """ Initialize a VoiceModels object. :param list[VoiceModel] customizations: An array of `VoiceModel` objects that provides information about each available custom voice model. The array is empty if the requesting service credentials own no custom voice models (if no language is specified) or own no custom voice models for the specified language. """ self.customizations = customizations @classmethod def _from_dict(cls, _dict): """Initialize a VoiceModels object from a json dictionary.""" args = {} if 'customizations' in _dict: args['customizations'] = [ VoiceModel._from_dict(x) for x in (_dict.get('customizations')) ] else: raise ValueError( 'Required property \'customizations\' not present in VoiceModels JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: _dict['customizations'] = [ x._to_dict() for x in self.customizations ] return _dict def __str__(self): """Return a `str` version of this VoiceModels object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Voices(object): """ Voices. :attr list[Voice] voices: A list of available voices. """ def __init__(self, voices): """ Initialize a Voices object. :param list[Voice] voices: A list of available voices. """ self.voices = voices @classmethod def _from_dict(cls, _dict): """Initialize a Voices object from a json dictionary.""" args = {} if 'voices' in _dict: args['voices'] = [ Voice._from_dict(x) for x in (_dict.get('voices')) ] else: raise ValueError( 'Required property \'voices\' not present in Voices JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'voices') and self.voices is not None: _dict['voices'] = [x._to_dict() for x in self.voices] return _dict def __str__(self): """Return a `str` version of this Voices object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Word(object): """ Word. :attr str word: A word from the custom voice model. :attr str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word. :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese entries](https://cloud.ibm.com/docs/services/text-to-speech/custom-rules.html#jaNotes). """ def __init__(self, word, translation, part_of_speech=None): """ Initialize a Word object. :param str word: A word from the custom voice model. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For more information, see [Working with Japanese entries](https://cloud.ibm.com/docs/services/text-to-speech/custom-rules.html#jaNotes). """ self.word = word self.translation = translation self.part_of_speech = part_of_speech @classmethod def _from_dict(cls, _dict): """Initialize a Word object from a json dictionary.""" args = {} if 'word' in _dict: args['word'] = _dict.get('word') else: raise ValueError( 'Required property \'word\' not present in Word JSON') if 'translation' in _dict: args['translation'] = _dict.get('translation') else: raise ValueError( 'Required property \'translation\' not present in Word JSON') if 'part_of_speech' in _dict: args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word if hasattr(self, 'translation') and self.translation is not None: _dict['translation'] = self.translation if hasattr(self, 'part_of_speech') and self.part_of_speech is not None: _dict['part_of_speech'] = self.part_of_speech return _dict def __str__(self): """Return a `str` version of this Word object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Words(object): """ Words. :attr list[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each object shows a word and its translation from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no words. """ def __init__(self, words): """ Initialize a Words object. :param list[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each object shows a word and its translation from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no words. """ self.words = words @classmethod def _from_dict(cls, _dict): """Initialize a Words object from a json dictionary.""" args = {} if 'words' in _dict: args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] else: raise ValueError( 'Required property \'words\' not present in Words JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: _dict['words'] = [x._to_dict() for x in self.words] return _dict def __str__(self): """Return a `str` version of this Words object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/assistant_v1.py0000644000076500000240000121606713451412131027410 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and integrated dialog tools to create conversation flows between your apps and your users. """ from __future__ import absolute_import import json from .watson_service import datetime_to_string, string_to_datetime from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class AssistantV1(WatsonService): """The Assistant V1 service.""" default_url = 'https://gateway.watsonplatform.net/assistant/api' def __init__( self, version, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Assistant service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/assistant/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='conversation', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Assistant') self.version = version ######################### # Message ######################### def message(self, workspace_id, input=None, alternate_intents=None, context=None, entities=None, intents=None, output=None, nodes_visited_details=None, **kwargs): """ Get response to user input. Send user input to a workspace and receive a response. There is no rate limit for this operation. :param str workspace_id: Unique identifier of the workspace. :param InputData input: An input object that includes the input text. :param bool alternate_intents: Whether to return more than one intent. Set to `true` to return all matching intents. :param Context context: State information for the conversation. To maintain state, include the context from the previous response. :param list[RuntimeEntity] entities: Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :param list[RuntimeIntent] intents: Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. :param OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. :param bool nodes_visited_details: Whether to include additional diagnostic information about the dialog nodes that were visited during processing of the message. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if input is not None: input = self._convert_model(input, InputData) if context is not None: context = self._convert_model(context, Context) if entities is not None: entities = [self._convert_model(x, RuntimeEntity) for x in entities] if intents is not None: intents = [self._convert_model(x, RuntimeIntent) for x in intents] if output is not None: output = self._convert_model(output, OutputData) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=message' params = { 'version': self.version, 'nodes_visited_details': nodes_visited_details } data = { 'input': input, 'alternate_intents': alternate_intents, 'context': context, 'entities': entities, 'intents': intents, 'output': output } url = '/v1/workspaces/{0}/message'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Workspaces ######################### def create_workspace(self, name=None, description=None, language=None, intents=None, entities=None, dialog_nodes=None, counterexamples=None, metadata=None, learning_opt_out=None, system_settings=None, **kwargs): """ Create workspace. 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: The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters. :param str description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param str language: The language of the workspace. :param list[CreateIntent] intents: An array of objects defining the intents for the workspace. :param list[CreateEntity] entities: An array of objects defining the entities for the workspace. :param list[CreateDialogNode] dialog_nodes: An array of objects defining the nodes in the dialog. :param list[CreateCounterexample] counterexamples: An array of objects defining input examples that have been marked as irrelevant input. :param object metadata: Any metadata related to the workspace. :param bool learning_opt_out: Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. :param WorkspaceSystemSettings system_settings: Global settings for the workspace. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if intents is not None: intents = [self._convert_model(x, CreateIntent) for x in intents] if entities is not None: entities = [self._convert_model(x, CreateEntity) for x in entities] if dialog_nodes is not None: dialog_nodes = [ self._convert_model(x, CreateDialogNode) for x in dialog_nodes ] if counterexamples is not None: counterexamples = [ self._convert_model(x, CreateCounterexample) for x in counterexamples ] if system_settings is not None: system_settings = self._convert_model(system_settings, WorkspaceSystemSettings) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_workspace' params = {'version': self.version} data = { 'name': name, 'description': description, 'language': language, 'intents': intents, 'entities': entities, 'dialog_nodes': dialog_nodes, 'counterexamples': counterexamples, 'metadata': metadata, 'learning_opt_out': learning_opt_out, 'system_settings': system_settings } url = '/v1/workspaces' response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_workspace(self, workspace_id, **kwargs): """ 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 :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_workspace' params = {'version': self.version} url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_workspace(self, workspace_id, export=None, include_audit=None, sort=None, **kwargs): """ 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: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param str sort: Indicates how the returned workspace data will be sorted. This parameter is valid only if **export**=`true`. Specify `sort=stable` to sort all workspace objects by unique identifier, in ascending alphabetical order. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_workspace' params = { 'version': self.version, 'export': export, 'include_audit': include_audit, 'sort': sort } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_workspaces(self, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ 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: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param 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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_workspaces' params = { 'version': self.version, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_workspace(self, workspace_id, name=None, description=None, language=None, intents=None, entities=None, dialog_nodes=None, counterexamples=None, metadata=None, learning_opt_out=None, system_settings=None, append=None, **kwargs): """ Update workspace. 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: The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters. :param str description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param str language: The language of the workspace. :param list[CreateIntent] intents: An array of objects defining the intents for the workspace. :param list[CreateEntity] entities: An array of objects defining the entities for the workspace. :param list[CreateDialogNode] dialog_nodes: An array of objects defining the nodes in the dialog. :param list[CreateCounterexample] counterexamples: An array of objects defining input examples that have been marked as irrelevant input. :param object metadata: Any metadata related to the workspace. :param bool learning_opt_out: Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. :param WorkspaceSystemSettings system_settings: Global settings for the workspace. :param bool append: Whether the new data is to be appended to the existing data in the workspace. If **append**=`false`, elements included in the new data completely replace the corresponding existing elements, including all subelements. For example, if the new data includes **entities** and **append**=`false`, all existing entities in the workspace are discarded and replaced with the new entities. If **append**=`true`, existing elements are preserved, and the new elements are added. If any elements in the new data collide with existing elements, the update request fails. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intents is not None: intents = [self._convert_model(x, CreateIntent) for x in intents] if entities is not None: entities = [self._convert_model(x, CreateEntity) for x in entities] if dialog_nodes is not None: dialog_nodes = [ self._convert_model(x, CreateDialogNode) for x in dialog_nodes ] if counterexamples is not None: counterexamples = [ self._convert_model(x, CreateCounterexample) for x in counterexamples ] if system_settings is not None: system_settings = self._convert_model(system_settings, WorkspaceSystemSettings) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_workspace' params = {'version': self.version, 'append': append} data = { 'name': name, 'description': description, 'language': language, 'intents': intents, 'entities': entities, 'dialog_nodes': dialog_nodes, 'counterexamples': counterexamples, 'metadata': metadata, 'learning_opt_out': learning_opt_out, 'system_settings': system_settings } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Intents ######################### def create_intent(self, workspace_id, intent, description=None, examples=None, **kwargs): """ Create intent. Create a new intent. 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 following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. :param str description: The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param list[CreateExample] examples: An array of user input examples for the intent. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') if examples is not None: examples = [self._convert_model(x, CreateExample) for x in examples] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_intent' params = {'version': self.version} data = { 'intent': intent, 'description': description, 'examples': examples } url = '/v1/workspaces/{0}/intents'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_intent(self, workspace_id, intent, **kwargs): """ 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. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_intent' params = {'version': self.version} url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_intent(self, workspace_id, intent, export=None, include_audit=None, **kwargs): """ 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. :param bool export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_intent' params = { 'version': self.version, 'export': export, 'include_audit': include_audit } url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_intents(self, workspace_id, export=None, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ 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: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param int page_limit: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned intents will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_intents' params = { 'version': self.version, 'export': export, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces/{0}/intents'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_intent(self, workspace_id, intent, new_intent=None, new_description=None, new_examples=None, **kwargs): """ Update intent. Update an existing intent with new or modified data. You must provide component objects defining the content of the updated intent. 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. :param str new_intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. :param str new_description: The description of the intent. :param list[CreateExample] new_examples: An array of user input examples for the intent. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') if new_examples is not None: new_examples = [ self._convert_model(x, CreateExample) for x in new_examples ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_intent' params = {'version': self.version} data = { 'intent': new_intent, 'description': new_description, 'examples': new_examples } url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Examples ######################### def create_example(self, workspace_id, intent, text, mentions=None, **kwargs): """ Create user input example. Add a new user input example to 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. :param str text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 1024 characters. :param list[Mentions] mentions: An array of contextual entity mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') if text is None: raise ValueError('text must be provided') if mentions is not None: mentions = [self._convert_model(x, Mentions) for x in mentions] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_example' params = {'version': self.version} data = {'text': text, 'mentions': mentions} url = '/v1/workspaces/{0}/intents/{1}/examples'.format( *self._encode_path_vars(workspace_id, intent)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_example(self, workspace_id, intent, text, **kwargs): """ 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. :param str text: The text of the user input example. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_example' params = {'version': self.version} url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_example(self, workspace_id, intent, text, include_audit=None, **kwargs): """ 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. :param str text: The text of the user input example. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_example' params = {'version': self.version, 'include_audit': include_audit} url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_examples(self, workspace_id, intent, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ List user input examples. 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. :param int page_limit: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned examples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_examples' params = { 'version': self.version, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces/{0}/intents/{1}/examples'.format( *self._encode_path_vars(workspace_id, intent)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_example(self, workspace_id, intent, text, new_text=None, new_mentions=None, **kwargs): """ Update user input example. Update the text of a user input example. 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. :param str text: The text of the user input example. :param str new_text: The text of the user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 1024 characters. :param list[Mentions] new_mentions: An array of contextual entity mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') if text is None: raise ValueError('text must be provided') if new_mentions is not None: new_mentions = [ self._convert_model(x, Mentions) for x in new_mentions ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_example' params = {'version': self.version} data = {'text': new_text, 'mentions': new_mentions} url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Counterexamples ######################### def create_counterexample(self, workspace_id, text, **kwargs): """ Create counterexample. Add a new counterexample to 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 marked as irrelevant input. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters - It cannot consist of only whitespace characters - It must be no longer than 1024 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_counterexample' params = {'version': self.version} data = {'text': text} url = '/v1/workspaces/{0}/counterexamples'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_counterexample(self, workspace_id, text, **kwargs): """ Delete counterexample. 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, `What are you wearing?`). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_counterexample' params = {'version': self.version} url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_counterexample(self, workspace_id, text, include_audit=None, **kwargs): """ Get counterexample. 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, `What are you wearing?`). :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_counterexample' params = {'version': self.version, 'include_audit': include_audit} url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_counterexamples(self, workspace_id, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ List counterexamples. 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: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned counterexamples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_counterexamples' params = { 'version': self.version, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces/{0}/counterexamples'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_counterexample(self, workspace_id, text, new_text=None, **kwargs): """ Update counterexample. Update the text of a counterexample. 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, `What are you wearing?`). :param str new_text: The text of a user input counterexample. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_counterexample' params = {'version': self.version} data = {'text': new_text} url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Entities ######################### def create_entity(self, workspace_id, entity, description=None, metadata=None, values=None, fuzzy_match=None, **kwargs): """ Create entity. Create a new entity, or enable 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. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It must be no longer than 64 characters. If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). :param str description: The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param object metadata: Any metadata related to the value. :param list[CreateValue] values: An array of objects describing the entity values. :param bool fuzzy_match: Whether to use fuzzy matching for the entity. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if values is not None: values = [self._convert_model(x, CreateValue) for x in values] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_entity' params = {'version': self.version} data = { 'entity': entity, 'description': description, 'metadata': metadata, 'values': values, 'fuzzy_match': fuzzy_match } url = '/v1/workspaces/{0}/entities'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_entity(self, workspace_id, entity, **kwargs): """ 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. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_entity' params = {'version': self.version} url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_entity(self, workspace_id, entity, export=None, include_audit=None, **kwargs): """ 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. :param bool export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_entity' params = { 'version': self.version, 'export': export, 'include_audit': include_audit } url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_entities(self, workspace_id, export=None, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ 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: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param int page_limit: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned entities will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_entities' params = { 'version': self.version, 'export': export, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces/{0}/entities'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_entity(self, workspace_id, entity, new_entity=None, new_description=None, new_metadata=None, new_fuzzy_match=None, new_values=None, **kwargs): """ Update entity. Update an existing entity with new or modified data. You must provide component objects defining the content of the updated 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. :param str new_entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 64 characters. :param str new_description: The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param object new_metadata: Any metadata related to the entity. :param bool new_fuzzy_match: Whether to use fuzzy matching for the entity. :param list[CreateValue] new_values: An array of entity values. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if new_values is not None: new_values = [ self._convert_model(x, CreateValue) for x in new_values ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_entity' params = {'version': self.version} data = { 'entity': new_entity, 'description': new_description, 'metadata': new_metadata, 'fuzzy_match': new_fuzzy_match, 'values': new_values } url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Mentions ######################### def list_mentions(self, workspace_id, entity, export=None, include_audit=None, **kwargs): """ List entity mentions. 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. :param bool export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_mentions' params = { 'version': self.version, 'export': export, 'include_audit': include_audit } url = '/v1/workspaces/{0}/entities/{1}/mentions'.format( *self._encode_path_vars(workspace_id, entity)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # Values ######################### def create_value(self, workspace_id, entity, value, metadata=None, synonyms=None, patterns=None, value_type=None, **kwargs): """ Add entity value. Create a new value for 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. :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param object metadata: Any metadata related to the entity value. :param list[str] synonyms: An array containing any synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param list[str] patterns: An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). :param str value_type: Specifies the type of value. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_value' params = {'version': self.version} data = { 'value': value, 'metadata': metadata, 'synonyms': synonyms, 'patterns': patterns, 'type': value_type } url = '/v1/workspaces/{0}/entities/{1}/values'.format( *self._encode_path_vars(workspace_id, entity)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_value(self, workspace_id, entity, value, **kwargs): """ 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. :param str value: The text of the entity value. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_value' params = {'version': self.version} url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_value(self, workspace_id, entity, value, export=None, include_audit=None, **kwargs): """ 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. :param str value: The text of the entity value. :param bool export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_value' params = { 'version': self.version, 'export': export, 'include_audit': include_audit } url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_values(self, workspace_id, entity, export=None, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ 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. :param bool export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only information about the element itself. If **export**=`true`, all content, including subelements, is included. :param int page_limit: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned entity values will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_values' params = { 'version': self.version, 'export': export, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces/{0}/entities/{1}/values'.format( *self._encode_path_vars(workspace_id, entity)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_value(self, workspace_id, entity, value, new_value=None, new_metadata=None, new_type=None, new_synonyms=None, new_patterns=None, **kwargs): """ Update entity value. Update an existing entity value with new or modified data. You must provide component objects defining the content of the updated 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. :param str value: The text of the entity value. :param str new_value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param object new_metadata: Any metadata related to the entity value. :param str new_type: Specifies the type of value. :param list[str] new_synonyms: An array of synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param list[str] new_patterns: An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_value' params = {'version': self.version} data = { 'value': new_value, 'metadata': new_metadata, 'type': new_type, 'synonyms': new_synonyms, 'patterns': new_patterns } url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Synonyms ######################### def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): """ Add entity value synonym. Add a new synonym to 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. :param str value: The text of the entity value. :param str synonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_synonym' params = {'version': self.version} data = {'synonym': synonym} url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( *self._encode_path_vars(workspace_id, entity, value)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): """ 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. :param str value: The text of the entity value. :param str synonym: The text of the synonym. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_synonym' params = {'version': self.version} url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_synonym(self, workspace_id, entity, value, synonym, include_audit=None, **kwargs): """ 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. :param str value: The text of the entity value. :param str synonym: The text of the synonym. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_synonym' params = {'version': self.version, 'include_audit': include_audit} url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_synonyms(self, workspace_id, entity, value, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ 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. :param str value: The text of the entity value. :param int page_limit: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned entity value synonyms will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_synonyms' params = { 'version': self.version, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( *self._encode_path_vars(workspace_id, entity, value)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_synonym(self, workspace_id, entity, value, synonym, new_synonym=None, **kwargs): """ Update entity value synonym. Update an existing entity value synonym with new text. 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. :param str value: The text of the entity value. :param str synonym: The text of the synonym. :param str new_synonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_synonym' params = {'version': self.version} data = {'synonym': new_synonym} url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Dialog nodes ######################### def create_dialog_node(self, workspace_id, dialog_node, description=None, conditions=None, parent=None, previous_sibling=None, output=None, context=None, metadata=None, next_step=None, actions=None, title=None, node_type=None, event_name=None, variable=None, digress_in=None, digress_out=None, digress_out_slots=None, user_label=None, **kwargs): """ Create dialog node. Create a new dialog node. 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 following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 1024 characters. :param str description: The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param str conditions: The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. :param str parent: The ID of the parent dialog node. :param str previous_sibling: The ID of the previous dialog node. :param DialogNodeOutput output: The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). :param object context: The context for the dialog node. :param object metadata: The metadata for the dialog node. :param DialogNodeNextStep next_step: The next step to execute following this dialog node. :param list[DialogNodeAction] actions: An array of objects describing any actions to be invoked by the dialog node. :param str title: The alias used to identify the dialog node. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 64 characters. :param str node_type: How the dialog node is processed. :param str event_name: How an `event_handler` node is processed. :param str variable: The location in the dialog context where output is stored. :param str digress_in: Whether this top-level dialog node can be digressed into. :param str digress_out: Whether this dialog node can be returned to after a digression. :param str digress_out_slots: Whether the user can digress to top-level nodes while filling out slots. :param str user_label: A label that can be displayed externally to describe the purpose of the node to users. This string must be no longer than 512 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node must be provided') if output is not None: output = self._convert_model(output, DialogNodeOutput) if next_step is not None: next_step = self._convert_model(next_step, DialogNodeNextStep) if actions is not None: actions = [ self._convert_model(x, DialogNodeAction) for x in actions ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=create_dialog_node' params = {'version': self.version} data = { 'dialog_node': dialog_node, 'description': description, 'conditions': conditions, 'parent': parent, 'previous_sibling': previous_sibling, 'output': output, 'context': context, 'metadata': metadata, 'next_step': next_step, 'actions': actions, 'title': title, 'type': node_type, 'event_name': event_name, 'variable': variable, 'digress_in': digress_in, 'digress_out': digress_out, 'digress_out_slots': digress_out_slots, 'user_label': user_label } url = '/v1/workspaces/{0}/dialog_nodes'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): """ 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`). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_dialog_node' params = {'version': self.version} url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response def get_dialog_node(self, workspace_id, dialog_node, include_audit=None, **kwargs): """ 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`). :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=get_dialog_node' params = {'version': self.version, 'include_audit': include_audit} url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_dialog_nodes(self, workspace_id, page_limit=None, include_count=None, sort=None, cursor=None, include_audit=None, **kwargs): """ 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: The number of records to return in each page of results. :param bool include_count: Whether to include information about the number of records returned. :param str sort: The attribute by which returned dialog nodes will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). :param str cursor: A token identifying the page of results to retrieve. :param bool include_audit: Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_dialog_nodes' params = { 'version': self.version, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces/{0}/dialog_nodes'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def update_dialog_node(self, workspace_id, dialog_node, new_dialog_node=None, new_description=None, new_conditions=None, new_parent=None, new_previous_sibling=None, new_output=None, new_context=None, new_metadata=None, new_next_step=None, new_title=None, new_type=None, new_event_name=None, new_variable=None, new_actions=None, new_digress_in=None, new_digress_out=None, new_digress_out_slots=None, new_user_label=None, **kwargs): """ Update dialog node. Update an existing dialog node with new or modified data. 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`). :param str new_dialog_node: The dialog node ID. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 1024 characters. :param str new_description: The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param str new_conditions: The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. :param str new_parent: The ID of the parent dialog node. :param str new_previous_sibling: The ID of the previous sibling dialog node. :param DialogNodeOutput new_output: The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). :param object new_context: The context for the dialog node. :param object new_metadata: The metadata for the dialog node. :param DialogNodeNextStep new_next_step: The next step to execute following this dialog node. :param str new_title: The alias used to identify the dialog node. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 64 characters. :param str new_type: How the dialog node is processed. :param str new_event_name: How an `event_handler` node is processed. :param str new_variable: The location in the dialog context where output is stored. :param list[DialogNodeAction] new_actions: An array of objects describing any actions to be invoked by the dialog node. :param str new_digress_in: Whether this top-level dialog node can be digressed into. :param str new_digress_out: Whether this dialog node can be returned to after a digression. :param str new_digress_out_slots: Whether the user can digress to top-level nodes while filling out slots. :param str new_user_label: A label that can be displayed externally to describe the purpose of the node to users. This string must be no longer than 512 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node must be provided') if new_output is not None: new_output = self._convert_model(new_output, DialogNodeOutput) if new_next_step is not None: new_next_step = self._convert_model(new_next_step, DialogNodeNextStep) if new_actions is not None: new_actions = [ self._convert_model(x, DialogNodeAction) for x in new_actions ] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=update_dialog_node' params = {'version': self.version} data = { 'dialog_node': new_dialog_node, 'description': new_description, 'conditions': new_conditions, 'parent': new_parent, 'previous_sibling': new_previous_sibling, 'output': new_output, 'context': new_context, 'metadata': new_metadata, 'next_step': new_next_step, 'title': new_title, 'type': new_type, 'event_name': new_event_name, 'variable': new_variable, 'actions': new_actions, 'digress_in': new_digress_in, 'digress_out': new_digress_out, 'digress_out_slots': new_digress_out_slots, 'user_label': new_user_label } url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) response = self.request( method='POST', url=url, headers=headers, params=params, json=data, accept_json=True) return response ######################### # Logs ######################### def list_all_logs(self, filter, sort=None, page_limit=None, cursor=None, **kwargs): """ 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 includes a value for `language`, as well as a value for `workspace_id` or `request.context.metadata.deployment`. For more information, see the [documentation](https://cloud.ibm.com/docs/services/assistant/filter-reference.html#filter-query-syntax). :param str sort: How to sort the returned log events. You can sort by **request_timestamp**. To reverse the sort order, prefix the parameter value with a minus sign (`-`). :param int page_limit: The number of records to return in each page of results. :param str cursor: A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if filter is None: raise ValueError('filter must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_all_logs' params = { 'version': self.version, 'filter': filter, 'sort': sort, 'page_limit': page_limit, 'cursor': cursor } url = '/v1/logs' response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response def list_logs(self, workspace_id, sort=None, filter=None, page_limit=None, cursor=None, **kwargs): """ 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: How to sort the returned log events. You can sort by **request_timestamp**. To reverse the sort order, prefix the parameter value with a minus sign (`-`). :param str filter: A cacheable parameter that limits the results to those matching the specified filter. For more information, see the [documentation](https://cloud.ibm.com/docs/services/assistant/filter-reference.html#filter-query-syntax). :param int page_limit: The number of records to return in each page of results. :param str cursor: A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if workspace_id is None: raise ValueError('workspace_id must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=list_logs' params = { 'version': self.version, 'sort': sort, 'filter': filter, 'page_limit': page_limit, 'cursor': cursor } url = '/v1/workspaces/{0}/logs'.format( *self._encode_path_vars(workspace_id)) response = self.request( method='GET', url=url, headers=headers, params=params, accept_json=True) return response ######################### # User data ######################### def delete_user_data(self, customer_id, **kwargs): """ Delete labeled data. Deletes all data associated with a specified customer ID. The method has no effect if no data is associated with the customer ID. You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes data. For more information about personal data and customer IDs, see [Information security](https://cloud.ibm.com/docs/services/assistant/information-security.html). :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')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=conversation;service_version=V1;operation_id=delete_user_data' params = {'version': self.version, 'customer_id': customer_id} url = '/v1/user_data' response = self.request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) return response ############################################################################## # Models ############################################################################## class CaptureGroup(object): """ CaptureGroup. :attr str group: A recognized capture group for the entity. :attr list[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ def __init__(self, group, location=None): """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. :param list[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a CaptureGroup object from a json dictionary.""" args = {} if 'group' in _dict: args['group'] = _dict.get('group') else: raise ValueError( 'Required property \'group\' not present in CaptureGroup JSON') if 'location' in _dict: args['location'] = _dict.get('location') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'group') and self.group is not None: _dict['group'] = self.group if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location return _dict def __str__(self): """Return a `str` version of this CaptureGroup object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Context(object): """ State information for the conversation. To maintain state, include the context from the previous response. :attr str conversation_id: (optional) The unique identifier of the conversation. :attr SystemResponse system: (optional) For internal use only. :attr MessageContextMetadata metadata: (optional) Metadata related to the message. """ def __init__(self, conversation_id=None, system=None, metadata=None, **kwargs): """ Initialize a Context object. :param str conversation_id: (optional) The unique identifier of the conversation. :param SystemResponse system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. :param **kwargs: (optional) Any additional properties. """ self.conversation_id = conversation_id self.system = system self.metadata = metadata for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a Context object from a json dictionary.""" args = {} xtra = _dict.copy() if 'conversation_id' in _dict: args['conversation_id'] = _dict.get('conversation_id') del xtra['conversation_id'] if 'system' in _dict: args['system'] = SystemResponse._from_dict(_dict.get('system')) del xtra['system'] if 'metadata' in _dict: args['metadata'] = MessageContextMetadata._from_dict( _dict.get('metadata')) del xtra['metadata'] args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'conversation_id') and self.conversation_id is not None: _dict['conversation_id'] = self.conversation_id if hasattr(self, 'system') and self.system is not None: _dict['system'] = self.system._to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata._to_dict() if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {'conversation_id', 'system', 'metadata'} if not hasattr(self, '_additionalProperties'): super(Context, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(Context, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this Context object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Counterexample(object): """ Counterexample. :attr str text: The text of the counterexample. :attr datetime created: (optional) The timestamp for creation of the counterexample. :attr datetime updated: (optional) The timestamp for the last update to the counterexample. """ def __init__(self, text, created=None, updated=None): """ Initialize a Counterexample object. :param str text: The text of the counterexample. :param datetime created: (optional) The timestamp for creation of the counterexample. :param datetime updated: (optional) The timestamp for the last update to the counterexample. """ self.text = text self.created = created self.updated = updated @classmethod def _from_dict(cls, _dict): """Initialize a Counterexample object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in Counterexample JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) return _dict def __str__(self): """Return a `str` version of this Counterexample object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CounterexampleCollection(object): """ CounterexampleCollection. :attr list[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, counterexamples, pagination): """ Initialize a CounterexampleCollection object. :param list[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :param Pagination pagination: The pagination data for the returned objects. """ self.counterexamples = counterexamples self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} if 'counterexamples' in _dict: args['counterexamples'] = [ Counterexample._from_dict(x) for x in (_dict.get('counterexamples')) ] else: raise ValueError( 'Required property \'counterexamples\' not present in CounterexampleCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in CounterexampleCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'counterexamples') and self.counterexamples is not None: _dict['counterexamples'] = [ x._to_dict() for x in self.counterexamples ] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this CounterexampleCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CreateCounterexample(object): """ CreateCounterexample. :attr str text: The text of a user input marked as irrelevant input. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters - It cannot consist of only whitespace characters - It must be no longer than 1024 characters. """ def __init__(self, text): """ Initialize a CreateCounterexample object. :param str text: The text of a user input marked as irrelevant input. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters - It cannot consist of only whitespace characters - It must be no longer than 1024 characters. """ self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a CreateCounterexample object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in CreateCounterexample JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this CreateCounterexample object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CreateDialogNode(object): """ CreateDialogNode. :attr str dialog_node: The dialog node ID. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 1024 characters. :attr str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :attr str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. :attr str parent: (optional) The ID of the parent dialog node. :attr str previous_sibling: (optional) The ID of the previous dialog node. :attr DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). :attr object context: (optional) The context for the dialog node. :attr object metadata: (optional) The metadata for the dialog node. :attr DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. :attr list[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :attr str title: (optional) The alias used to identify the dialog node. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 64 characters. :attr str node_type: (optional) How the dialog node is processed. :attr str event_name: (optional) How an `event_handler` node is processed. :attr str variable: (optional) The location in the dialog context where output is stored. :attr str digress_in: (optional) Whether this top-level dialog node can be digressed into. :attr str digress_out: (optional) Whether this dialog node can be returned to after a digression. :attr str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :attr str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. This string must be no longer than 512 characters. """ def __init__(self, dialog_node, description=None, conditions=None, parent=None, previous_sibling=None, output=None, context=None, metadata=None, next_step=None, actions=None, title=None, node_type=None, event_name=None, variable=None, digress_in=None, digress_out=None, digress_out_slots=None, user_label=None): """ Initialize a CreateDialogNode object. :param str dialog_node: The dialog node ID. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 1024 characters. :param str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. :param str parent: (optional) The ID of the parent dialog node. :param str previous_sibling: (optional) The ID of the previous dialog node. :param DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). :param object context: (optional) The context for the dialog node. :param object metadata: (optional) The metadata for the dialog node. :param DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. :param list[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :param str title: (optional) The alias used to identify the dialog node. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 64 characters. :param str node_type: (optional) How the dialog node is processed. :param str event_name: (optional) How an `event_handler` node is processed. :param str variable: (optional) The location in the dialog context where output is stored. :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. :param str digress_out: (optional) Whether this dialog node can be returned to after a digression. :param str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :param str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. This string must be no longer than 512 characters. """ self.dialog_node = dialog_node self.description = description self.conditions = conditions self.parent = parent self.previous_sibling = previous_sibling self.output = output self.context = context self.metadata = metadata self.next_step = next_step self.actions = actions self.title = title self.node_type = node_type self.event_name = event_name self.variable = variable self.digress_in = digress_in self.digress_out = digress_out self.digress_out_slots = digress_out_slots self.user_label = user_label @classmethod def _from_dict(cls, _dict): """Initialize a CreateDialogNode object from a json dictionary.""" args = {} if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') else: raise ValueError( 'Required property \'dialog_node\' not present in CreateDialogNode JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') if 'conditions' in _dict: args['conditions'] = _dict.get('conditions') if 'parent' in _dict: args['parent'] = _dict.get('parent') if 'previous_sibling' in _dict: args['previous_sibling'] = _dict.get('previous_sibling') if 'output' in _dict: args['output'] = DialogNodeOutput._from_dict(_dict.get('output')) if 'context' in _dict: args['context'] = _dict.get('context') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'next_step' in _dict: args['next_step'] = DialogNodeNextStep._from_dict( _dict.get('next_step')) if 'actions' in _dict: args['actions'] = [ DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) ] if 'title' in _dict: args['title'] = _dict.get('title') if 'type' in _dict or 'node_type' in _dict: args['node_type'] = _dict.get('type') or _dict.get('node_type') if 'event_name' in _dict: args['event_name'] = _dict.get('event_name') if 'variable' in _dict: args['variable'] = _dict.get('variable') if 'digress_in' in _dict: args['digress_in'] = _dict.get('digress_in') if 'digress_out' in _dict: args['digress_out'] = _dict.get('digress_out') if 'digress_out_slots' in _dict: args['digress_out_slots'] = _dict.get('digress_out_slots') if 'user_label' in _dict: args['user_label'] = _dict.get('user_label') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'conditions') and self.conditions is not None: _dict['conditions'] = self.conditions if hasattr(self, 'parent') and self.parent is not None: _dict['parent'] = self.parent if hasattr(self, 'previous_sibling') and self.previous_sibling is not None: _dict['previous_sibling'] = self.previous_sibling if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output._to_dict() if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'next_step') and self.next_step is not None: _dict['next_step'] = self.next_step._to_dict() if hasattr(self, 'actions') and self.actions is not None: _dict['actions'] = [x._to_dict() for x in self.actions] if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'node_type') and self.node_type is not None: _dict['type'] = self.node_type if hasattr(self, 'event_name') and self.event_name is not None: _dict['event_name'] = self.event_name if hasattr(self, 'variable') and self.variable is not None: _dict['variable'] = self.variable if hasattr(self, 'digress_in') and self.digress_in is not None: _dict['digress_in'] = self.digress_in if hasattr(self, 'digress_out') and self.digress_out is not None: _dict['digress_out'] = self.digress_out if hasattr(self, 'digress_out_slots') and self.digress_out_slots is not None: _dict['digress_out_slots'] = self.digress_out_slots if hasattr(self, 'user_label') and self.user_label is not None: _dict['user_label'] = self.user_label return _dict def __str__(self): """Return a `str` version of this CreateDialogNode object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CreateEntity(object): """ CreateEntity. :attr str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It must be no longer than 64 characters. If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). :attr str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :attr object metadata: (optional) Any metadata related to the value. :attr list[CreateValue] values: (optional) An array of objects describing the entity values. :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. """ def __init__(self, entity, description=None, metadata=None, values=None, fuzzy_match=None): """ Initialize a CreateEntity object. :param str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - It must be no longer than 64 characters. If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). :param str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param object metadata: (optional) Any metadata related to the value. :param list[CreateValue] values: (optional) An array of objects describing the entity values. :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. """ self.entity = entity self.description = description self.metadata = metadata self.values = values self.fuzzy_match = fuzzy_match @classmethod def _from_dict(cls, _dict): """Initialize a CreateEntity object from a json dictionary.""" args = {} if 'entity' in _dict: args['entity'] = _dict.get('entity') else: raise ValueError( 'Required property \'entity\' not present in CreateEntity JSON') if 'description' in _dict: args['description'] = _dict.get('description') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'values' in _dict: args['values'] = [ CreateValue._from_dict(x) for x in (_dict.get('values')) ] if 'fuzzy_match' in _dict: args['fuzzy_match'] = _dict.get('fuzzy_match') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entity') and self.entity is not None: _dict['entity'] = self.entity if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'values') and self.values is not None: _dict['values'] = [x._to_dict() for x in self.values] if hasattr(self, 'fuzzy_match') and self.fuzzy_match is not None: _dict['fuzzy_match'] = self.fuzzy_match return _dict def __str__(self): """Return a `str` version of this CreateEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CreateExample(object): """ CreateExample. :attr str text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 1024 characters. :attr list[Mentions] mentions: (optional) An array of contextual entity mentions. """ def __init__(self, text, mentions=None): """ Initialize a CreateExample object. :param str text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 1024 characters. :param list[Mentions] mentions: (optional) An array of contextual entity mentions. """ self.text = text self.mentions = mentions @classmethod def _from_dict(cls, _dict): """Initialize a CreateExample object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') else: raise ValueError( 'Required property \'text\' not present in CreateExample JSON') if 'mentions' in _dict: args['mentions'] = [ Mentions._from_dict(x) for x in (_dict.get('mentions')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'mentions') and self.mentions is not None: _dict['mentions'] = [x._to_dict() for x in self.mentions] return _dict def __str__(self): """Return a `str` version of this CreateExample object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CreateIntent(object): """ CreateIntent. :attr str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. :attr str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :attr list[CreateExample] examples: (optional) An array of user input examples for the intent. """ def __init__(self, intent, description=None, examples=None): """ Initialize a CreateIntent object. :param str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. :param list[CreateExample] examples: (optional) An array of user input examples for the intent. """ self.intent = intent self.description = description self.examples = examples @classmethod def _from_dict(cls, _dict): """Initialize a CreateIntent object from a json dictionary.""" args = {} if 'intent' in _dict: args['intent'] = _dict.get('intent') else: raise ValueError( 'Required property \'intent\' not present in CreateIntent JSON') if 'description' in _dict: args['description'] = _dict.get('description') if 'examples' in _dict: args['examples'] = [ CreateExample._from_dict(x) for x in (_dict.get('examples')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intent') and self.intent is not None: _dict['intent'] = self.intent if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict def __str__(self): """Return a `str` version of this CreateIntent object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class CreateValue(object): """ CreateValue. :attr str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :attr object metadata: (optional) Any metadata related to the entity value. :attr list[str] synonyms: (optional) An array containing any synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :attr list[str] patterns: (optional) An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). :attr str value_type: (optional) Specifies the type of value. """ def __init__(self, value, metadata=None, synonyms=None, patterns=None, value_type=None): """ Initialize a CreateValue object. :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param object metadata: (optional) Any metadata related to the entity value. :param list[str] synonyms: (optional) An array containing any synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. :param list[str] patterns: (optional) An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For more information about how to specify a pattern, see the [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). :param str value_type: (optional) Specifies the type of value. """ self.value = value self.metadata = metadata self.synonyms = synonyms self.patterns = patterns self.value_type = value_type @classmethod def _from_dict(cls, _dict): """Initialize a CreateValue object from a json dictionary.""" args = {} if 'value' in _dict: args['value'] = _dict.get('value') else: raise ValueError( 'Required property \'value\' not present in CreateValue JSON') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'synonyms' in _dict: args['synonyms'] = _dict.get('synonyms') if 'patterns' in _dict: args['patterns'] = _dict.get('patterns') if 'type' in _dict or 'value_type' in _dict: args['value_type'] = _dict.get('type') or _dict.get('value_type') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'synonyms') and self.synonyms is not None: _dict['synonyms'] = self.synonyms if hasattr(self, 'patterns') and self.patterns is not None: _dict['patterns'] = self.patterns if hasattr(self, 'value_type') and self.value_type is not None: _dict['type'] = self.value_type return _dict def __str__(self): """Return a `str` version of this CreateValue object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNode(object): """ DialogNode. :attr str dialog_node_id: The dialog node ID. :attr str description: (optional) The description of the dialog node. :attr str conditions: (optional) The condition that triggers the dialog node. :attr str parent: (optional) The ID of the parent dialog node. This property is not returned if the dialog node has no parent. :attr str previous_sibling: (optional) The ID of the previous sibling dialog node. This property is not returned if the dialog node has no previous sibling. :attr DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). :attr object context: (optional) The context (if defined) for the dialog node. :attr object metadata: (optional) Any metadata for the dialog node. :attr DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. :attr datetime created: (optional) The timestamp for creation of the dialog node. :attr datetime updated: (optional) The timestamp for the most recent update to the dialog node. :attr list[DialogNodeAction] actions: (optional) The actions for the dialog node. :attr str title: (optional) The alias used to identify the dialog node. :attr bool disabled: (optional) For internal use only. :attr str node_type: (optional) How the dialog node is processed. :attr str event_name: (optional) How an `event_handler` node is processed. :attr str variable: (optional) The location in the dialog context where output is stored. :attr str digress_in: (optional) Whether this top-level dialog node can be digressed into. :attr str digress_out: (optional) Whether this dialog node can be returned to after a digression. :attr str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :attr str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. This string must be no longer than 512 characters. """ def __init__(self, dialog_node_id, description=None, conditions=None, parent=None, previous_sibling=None, output=None, context=None, metadata=None, next_step=None, created=None, updated=None, actions=None, title=None, disabled=None, node_type=None, event_name=None, variable=None, digress_in=None, digress_out=None, digress_out_slots=None, user_label=None): """ Initialize a DialogNode object. :param str dialog_node_id: The dialog node ID. :param str description: (optional) The description of the dialog node. :param str conditions: (optional) The condition that triggers the dialog node. :param str parent: (optional) The ID of the parent dialog node. This property is not returned if the dialog node has no parent. :param str previous_sibling: (optional) The ID of the previous sibling dialog node. This property is not returned if the dialog node has no previous sibling. :param DialogNodeOutput output: (optional) The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). :param object context: (optional) The context (if defined) for the dialog node. :param object metadata: (optional) Any metadata for the dialog node. :param DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. :param datetime created: (optional) The timestamp for creation of the dialog node. :param datetime updated: (optional) The timestamp for the most recent update to the dialog node. :param list[DialogNodeAction] actions: (optional) The actions for the dialog node. :param str title: (optional) The alias used to identify the dialog node. :param bool disabled: (optional) For internal use only. :param str node_type: (optional) How the dialog node is processed. :param str event_name: (optional) How an `event_handler` node is processed. :param str variable: (optional) The location in the dialog context where output is stored. :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. :param str digress_out: (optional) Whether this dialog node can be returned to after a digression. :param str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :param str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. This string must be no longer than 512 characters. """ self.dialog_node_id = dialog_node_id self.description = description self.conditions = conditions self.parent = parent self.previous_sibling = previous_sibling self.output = output self.context = context self.metadata = metadata self.next_step = next_step self.created = created self.updated = updated self.actions = actions self.title = title self.disabled = disabled self.node_type = node_type self.event_name = event_name self.variable = variable self.digress_in = digress_in self.digress_out = digress_out self.digress_out_slots = digress_out_slots self.user_label = user_label @classmethod def _from_dict(cls, _dict): """Initialize a DialogNode object from a json dictionary.""" args = {} if 'dialog_node' in _dict or 'dialog_node_id' in _dict: args['dialog_node_id'] = _dict.get('dialog_node') or _dict.get( 'dialog_node_id') else: raise ValueError( 'Required property \'dialog_node\' not present in DialogNode JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') if 'conditions' in _dict: args['conditions'] = _dict.get('conditions') if 'parent' in _dict: args['parent'] = _dict.get('parent') if 'previous_sibling' in _dict: args['previous_sibling'] = _dict.get('previous_sibling') if 'output' in _dict: args['output'] = DialogNodeOutput._from_dict(_dict.get('output')) if 'context' in _dict: args['context'] = _dict.get('context') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'next_step' in _dict: args['next_step'] = DialogNodeNextStep._from_dict( _dict.get('next_step')) if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'actions' in _dict: args['actions'] = [ DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) ] if 'title' in _dict: args['title'] = _dict.get('title') if 'disabled' in _dict: args['disabled'] = _dict.get('disabled') if 'type' in _dict or 'node_type' in _dict: args['node_type'] = _dict.get('type') or _dict.get('node_type') if 'event_name' in _dict: args['event_name'] = _dict.get('event_name') if 'variable' in _dict: args['variable'] = _dict.get('variable') if 'digress_in' in _dict: args['digress_in'] = _dict.get('digress_in') if 'digress_out' in _dict: args['digress_out'] = _dict.get('digress_out') if 'digress_out_slots' in _dict: args['digress_out_slots'] = _dict.get('digress_out_slots') if 'user_label' in _dict: args['user_label'] = _dict.get('user_label') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_node_id') and self.dialog_node_id is not None: _dict['dialog_node'] = self.dialog_node_id if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'conditions') and self.conditions is not None: _dict['conditions'] = self.conditions if hasattr(self, 'parent') and self.parent is not None: _dict['parent'] = self.parent if hasattr(self, 'previous_sibling') and self.previous_sibling is not None: _dict['previous_sibling'] = self.previous_sibling if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output._to_dict() if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'next_step') and self.next_step is not None: _dict['next_step'] = self.next_step._to_dict() if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'actions') and self.actions is not None: _dict['actions'] = [x._to_dict() for x in self.actions] if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'disabled') and self.disabled is not None: _dict['disabled'] = self.disabled if hasattr(self, 'node_type') and self.node_type is not None: _dict['type'] = self.node_type if hasattr(self, 'event_name') and self.event_name is not None: _dict['event_name'] = self.event_name if hasattr(self, 'variable') and self.variable is not None: _dict['variable'] = self.variable if hasattr(self, 'digress_in') and self.digress_in is not None: _dict['digress_in'] = self.digress_in if hasattr(self, 'digress_out') and self.digress_out is not None: _dict['digress_out'] = self.digress_out if hasattr(self, 'digress_out_slots') and self.digress_out_slots is not None: _dict['digress_out_slots'] = self.digress_out_slots if hasattr(self, 'user_label') and self.user_label is not None: _dict['user_label'] = self.user_label return _dict def __str__(self): """Return a `str` version of this DialogNode object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeAction(object): """ DialogNodeAction. :attr str name: The name of the action. :attr str action_type: (optional) The type of action to invoke. :attr object parameters: (optional) A map of key/value pairs to be provided to the action. :attr str result_variable: The location in the dialog context where the result of the action is stored. :attr str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ def __init__(self, name, result_variable, action_type=None, parameters=None, credentials=None): """ Initialize a DialogNodeAction object. :param str name: The name of the action. :param str result_variable: The location in the dialog context where the result of the action is stored. :param str action_type: (optional) The type of action to invoke. :param object parameters: (optional) A map of key/value pairs to be provided to the action. :param str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ self.name = name self.action_type = action_type self.parameters = parameters self.result_variable = result_variable self.credentials = credentials @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeAction object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) if 'type' in _dict or 'action_type' in _dict: args['action_type'] = _dict.get('type') or _dict.get('action_type') if 'parameters' in _dict: args['parameters'] = _dict.get('parameters') if 'result_variable' in _dict: args['result_variable'] = _dict.get('result_variable') else: raise ValueError( 'Required property \'result_variable\' not present in DialogNodeAction JSON' ) if 'credentials' in _dict: args['credentials'] = _dict.get('credentials') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'action_type') and self.action_type is not None: _dict['type'] = self.action_type if hasattr(self, 'parameters') and self.parameters is not None: _dict['parameters'] = self.parameters if hasattr(self, 'result_variable') and self.result_variable is not None: _dict['result_variable'] = self.result_variable if hasattr(self, 'credentials') and self.credentials is not None: _dict['credentials'] = self.credentials return _dict def __str__(self): """Return a `str` version of this DialogNodeAction object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeCollection(object): """ An array of dialog nodes. :attr list[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, dialog_nodes, pagination): """ Initialize a DialogNodeCollection object. :param list[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ self.dialog_nodes = dialog_nodes self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ DialogNode._from_dict(x) for x in (_dict.get('dialog_nodes')) ] else: raise ValueError( 'Required property \'dialog_nodes\' not present in DialogNodeCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in DialogNodeCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: _dict['dialog_nodes'] = [x._to_dict() for x in self.dialog_nodes] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this DialogNodeCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeNextStep(object): """ The next step to execute following this dialog node. :attr str behavior: What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` - `skip_user_input` - `jump_to` - If the node is of type `event_handler` and its parent node is of type `slot` or `frame`, additional values are also valid: - if **event_name**=`filled` and the type of the parent node is `slot`: - `reprompt` - `skip_all_slots` - if **event_name**=`nomatch` and the type of the parent node is `slot`: - `reprompt` - `skip_slot` - `skip_all_slots` - if **event_name**=`generic` and the type of the parent node is `frame`: - `reprompt` - `skip_slot` - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. :attr str dialog_node: (optional) The ID of the dialog node to process next. This parameter is required if **behavior**=`jump_to`. :attr str selector: (optional) Which part of the dialog node to process next. """ def __init__(self, behavior, dialog_node=None, selector=None): """ Initialize a DialogNodeNextStep object. :param str behavior: What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` - `skip_user_input` - `jump_to` - If the node is of type `event_handler` and its parent node is of type `slot` or `frame`, additional values are also valid: - if **event_name**=`filled` and the type of the parent node is `slot`: - `reprompt` - `skip_all_slots` - if **event_name**=`nomatch` and the type of the parent node is `slot`: - `reprompt` - `skip_slot` - `skip_all_slots` - if **event_name**=`generic` and the type of the parent node is `frame`: - `reprompt` - `skip_slot` - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. :param str dialog_node: (optional) The ID of the dialog node to process next. This parameter is required if **behavior**=`jump_to`. :param str selector: (optional) Which part of the dialog node to process next. """ self.behavior = behavior self.dialog_node = dialog_node self.selector = selector @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} if 'behavior' in _dict: args['behavior'] = _dict.get('behavior') else: raise ValueError( 'Required property \'behavior\' not present in DialogNodeNextStep JSON' ) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') if 'selector' in _dict: args['selector'] = _dict.get('selector') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'behavior') and self.behavior is not None: _dict['behavior'] = self.behavior if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'selector') and self.selector is not None: _dict['selector'] = self.selector return _dict def __str__(self): """Return a `str` version of this DialogNodeNextStep object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutput(object): """ The output of the dialog node. For more information about how to specify dialog node output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). :attr list[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. """ def __init__(self, generic=None, modifiers=None, **kwargs): """ Initialize a DialogNodeOutput object. :param list[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. :param **kwargs: (optional) Any additional properties. """ self.generic = generic self.modifiers = modifiers for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutput object from a json dictionary.""" args = {} xtra = _dict.copy() if 'generic' in _dict: args['generic'] = [ DialogNodeOutputGeneric._from_dict(x) for x in (_dict.get('generic')) ] del xtra['generic'] if 'modifiers' in _dict: args['modifiers'] = DialogNodeOutputModifiers._from_dict( _dict.get('modifiers')) del xtra['modifiers'] args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: _dict['generic'] = [x._to_dict() for x in self.generic] if hasattr(self, 'modifiers') and self.modifiers is not None: _dict['modifiers'] = self.modifiers._to_dict() if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {'generic', 'modifiers'} if not hasattr(self, '_additionalProperties'): super(DialogNodeOutput, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(DialogNodeOutput, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this DialogNodeOutput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutputGeneric(object): """ DialogNodeOutputGeneric. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr list[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :attr str selection_policy: (optional) How a response is selected from the list, if more than one response is specified. Valid only when **response_type**=`text`. :attr str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. :attr int time: (optional) How long to pause, in milliseconds. The valid values are from 0 to 10000. Valid only when **response_type**=`pause`. :attr bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. Valid only when **response_type**=`pause`. :attr str source: (optional) The URL of the image. Required when **response_type**=`image`. :attr str title: (optional) An optional title to show before the response. Valid only when **response_type**=`image` or `option`. This string must be no longer than 512 characters. :attr str description: (optional) An optional description to show with the response. Valid only when **response_type**=`image` or `option`. This string must be no longer than 256 characters. :attr str preference: (optional) The preferred type of control to display, if supported by the channel. Valid only when **response_type**=`option`. :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. You can include up to 20 options. Required when **response_type**=`option`. :attr str message_to_human_agent: (optional) An optional message to be sent to the human agent who will be taking over the conversation. Valid only when **reponse_type**=`connect_to_agent`. This string must be no longer than 256 characters. """ def __init__(self, response_type, values=None, selection_policy=None, delimiter=None, time=None, typing=None, source=None, title=None, description=None, preference=None, options=None, message_to_human_agent=None): """ Initialize a DialogNodeOutputGeneric object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :param list[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :param str selection_policy: (optional) How a response is selected from the list, if more than one response is specified. Valid only when **response_type**=`text`. :param str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. :param int time: (optional) How long to pause, in milliseconds. The valid values are from 0 to 10000. Valid only when **response_type**=`pause`. :param bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. Valid only when **response_type**=`pause`. :param str source: (optional) The URL of the image. Required when **response_type**=`image`. :param str title: (optional) An optional title to show before the response. Valid only when **response_type**=`image` or `option`. This string must be no longer than 512 characters. :param str description: (optional) An optional description to show with the response. Valid only when **response_type**=`image` or `option`. This string must be no longer than 256 characters. :param str preference: (optional) The preferred type of control to display, if supported by the channel. Valid only when **response_type**=`option`. :param list[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. You can include up to 20 options. Required when **response_type**=`option`. :param str message_to_human_agent: (optional) An optional message to be sent to the human agent who will be taking over the conversation. Valid only when **reponse_type**=`connect_to_agent`. This string must be no longer than 256 characters. """ self.response_type = response_type self.values = values self.selection_policy = selection_policy self.delimiter = delimiter self.time = time self.typing = typing self.source = source self.title = title self.description = description self.preference = preference self.options = options self.message_to_human_agent = message_to_human_agent @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" args = {} if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGeneric JSON' ) if 'values' in _dict: args['values'] = [ DialogNodeOutputTextValuesElement._from_dict(x) for x in (_dict.get('values')) ] if 'selection_policy' in _dict: args['selection_policy'] = _dict.get('selection_policy') if 'delimiter' in _dict: args['delimiter'] = _dict.get('delimiter') if 'time' in _dict: args['time'] = _dict.get('time') if 'typing' in _dict: args['typing'] = _dict.get('typing') if 'source' in _dict: args['source'] = _dict.get('source') if 'title' in _dict: args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') if 'preference' in _dict: args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ DialogNodeOutputOptionsElement._from_dict(x) for x in (_dict.get('options')) ] if 'message_to_human_agent' in _dict: args['message_to_human_agent'] = _dict.get('message_to_human_agent') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type if hasattr(self, 'values') and self.values is not None: _dict['values'] = [x._to_dict() for x in self.values] if hasattr(self, 'selection_policy') and self.selection_policy is not None: _dict['selection_policy'] = self.selection_policy if hasattr(self, 'delimiter') and self.delimiter is not None: _dict['delimiter'] = self.delimiter if hasattr(self, 'time') and self.time is not None: _dict['time'] = self.time if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: _dict['options'] = [x._to_dict() for x in self.options] if hasattr(self, 'message_to_human_agent' ) and self.message_to_human_agent is not None: _dict['message_to_human_agent'] = self.message_to_human_agent return _dict def __str__(self): """Return a `str` version of this DialogNodeOutputGeneric object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutputModifiers(object): """ Options that modify how specified output is handled. :attr bool overwrite: (optional) Whether values in the output will overwrite output values in an array specified by previously executed dialog nodes. If this option is set to **false**, new values will be appended to previously specified values. """ def __init__(self, overwrite=None): """ Initialize a DialogNodeOutputModifiers object. :param bool overwrite: (optional) Whether values in the output will overwrite output values in an array specified by previously executed dialog nodes. If this option is set to **false**, new values will be appended to previously specified values. """ self.overwrite = overwrite @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} if 'overwrite' in _dict: args['overwrite'] = _dict.get('overwrite') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'overwrite') and self.overwrite is not None: _dict['overwrite'] = self.overwrite return _dict def __str__(self): """Return a `str` version of this DialogNodeOutputModifiers object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutputOptionsElement(object): """ DialogNodeOutputOptionsElement. :attr str label: The user-facing label for the option. :attr DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. """ def __init__(self, label, value): """ Initialize a DialogNodeOutputOptionsElement object. :param str label: The user-facing label for the option. :param DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. """ self.label = label self.value = value @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = _dict.get('label') else: raise ValueError( 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) if 'value' in _dict: args['value'] = DialogNodeOutputOptionsElementValue._from_dict( _dict.get('value')) else: raise ValueError( 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value._to_dict() return _dict def __str__(self): """Return a `str` version of this DialogNodeOutputOptionsElement object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutputOptionsElementValue(object): """ An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. :attr InputData input: (optional) An input object that includes the input text. """ def __init__(self, input=None): """ Initialize a DialogNodeOutputOptionsElementValue object. :param InputData input: (optional) An input object that includes the input text. """ self.input = input @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} if 'input' in _dict: args['input'] = InputData._from_dict(_dict.get('input')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: _dict['input'] = self.input._to_dict() return _dict def __str__(self): """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeOutputTextValuesElement(object): """ DialogNodeOutputTextValuesElement. :attr str text: (optional) The text of a response. This string can include newline characters (` `), Markdown tagging, or other special characters, if supported by the channel. It must be no longer than 4096 characters. """ def __init__(self, text=None): """ Initialize a DialogNodeOutputTextValuesElement object. :param str text: (optional) The text of a response. This string can include newline characters (` `), Markdown tagging, or other special characters, if supported by the channel. It must be no longer than 4096 characters. """ self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this DialogNodeOutputTextValuesElement object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogNodeVisitedDetails(object): """ DialogNodeVisitedDetails. :attr str dialog_node: (optional) A dialog node that was triggered during processing of the input message. :attr str title: (optional) The title of the dialog node. :attr str conditions: (optional) The conditions that trigger the dialog node. """ def __init__(self, dialog_node=None, title=None, conditions=None): """ Initialize a DialogNodeVisitedDetails object. :param str dialog_node: (optional) A dialog node that was triggered during processing of the input message. :param str title: (optional) The title of the dialog node. :param str conditions: (optional) The conditions that trigger the dialog node. """ self.dialog_node = dialog_node self.title = title self.conditions = conditions @classmethod def _from_dict(cls, _dict): """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') if 'title' in _dict: args['title'] = _dict.get('title') if 'conditions' in _dict: args['conditions'] = _dict.get('conditions') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'conditions') and self.conditions is not None: _dict['conditions'] = self.conditions return _dict def __str__(self): """Return a `str` version of this DialogNodeVisitedDetails object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogRuntimeResponseGeneric(object): """ DialogRuntimeResponseGeneric. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available for Premium users. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during the pause. :attr str source: (optional) The URL of the image. :attr str title: (optional) The title or introductory text to show before the response. :attr str description: (optional) The description to show with the the response. :attr str preference: (optional) The preferred type of control to display. :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :attr str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. :attr list[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. """ def __init__(self, response_type, text=None, time=None, typing=None, source=None, title=None, description=None, preference=None, options=None, message_to_human_agent=None, topic=None, suggestions=None): """ Initialize a DialogRuntimeResponseGeneric object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available for Premium users. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event during the pause. :param str source: (optional) The URL of the image. :param str title: (optional) The title or introductory text to show before the response. :param str description: (optional) The description to show with the the response. :param str preference: (optional) The preferred type of control to display. :param list[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :param str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. :param list[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. """ self.response_type = response_type self.text = text self.time = time self.typing = typing self.source = source self.title = title self.description = description self.preference = preference self.options = options self.message_to_human_agent = message_to_human_agent self.topic = topic self.suggestions = suggestions @classmethod def _from_dict(cls, _dict): """Initialize a DialogRuntimeResponseGeneric object from a json dictionary.""" args = {} if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: raise ValueError( 'Required property \'response_type\' not present in DialogRuntimeResponseGeneric JSON' ) if 'text' in _dict: args['text'] = _dict.get('text') if 'time' in _dict: args['time'] = _dict.get('time') if 'typing' in _dict: args['typing'] = _dict.get('typing') if 'source' in _dict: args['source'] = _dict.get('source') if 'title' in _dict: args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') if 'preference' in _dict: args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ DialogNodeOutputOptionsElement._from_dict(x) for x in (_dict.get('options')) ] if 'message_to_human_agent' in _dict: args['message_to_human_agent'] = _dict.get('message_to_human_agent') if 'topic' in _dict: args['topic'] = _dict.get('topic') if 'suggestions' in _dict: args['suggestions'] = [ DialogSuggestion._from_dict(x) for x in (_dict.get('suggestions')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'time') and self.time is not None: _dict['time'] = self.time if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: _dict['options'] = [x._to_dict() for x in self.options] if hasattr(self, 'message_to_human_agent' ) and self.message_to_human_agent is not None: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'suggestions') and self.suggestions is not None: _dict['suggestions'] = [x._to_dict() for x in self.suggestions] return _dict def __str__(self): """Return a `str` version of this DialogRuntimeResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogSuggestion(object): """ DialogSuggestion. :attr str label: The user-facing label for the disambiguation option. This label is taken from the **user_label** property of the corresponding dialog node. :attr DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. :attr object output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. """ def __init__(self, label, value, output=None): """ Initialize a DialogSuggestion object. :param str label: The user-facing label for the disambiguation option. This label is taken from the **user_label** property of the corresponding dialog node. :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. :param object output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. """ self.label = label self.value = value self.output = output @classmethod def _from_dict(cls, _dict): """Initialize a DialogSuggestion object from a json dictionary.""" args = {} if 'label' in _dict: args['label'] = _dict.get('label') else: raise ValueError( 'Required property \'label\' not present in DialogSuggestion JSON' ) if 'value' in _dict: args['value'] = DialogSuggestionValue._from_dict(_dict.get('value')) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' ) if 'output' in _dict: args['output'] = _dict.get('output') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value._to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output return _dict def __str__(self): """Return a `str` version of this DialogSuggestion object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DialogSuggestionValue(object): """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. :attr InputData input: (optional) An input object that includes the input text. :attr list[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. :attr list[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ def __init__(self, input=None, intents=None, entities=None): """ Initialize a DialogSuggestionValue object. :param InputData input: (optional) An input object that includes the input text. :param list[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. :param list[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ self.input = input self.intents = intents self.entities = entities @classmethod def _from_dict(cls, _dict): """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} if 'input' in _dict: args['input'] = InputData._from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'entities' in _dict: args['entities'] = [ RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: _dict['input'] = self.input._to_dict() if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] return _dict def __str__(self): """Return a `str` version of this DialogSuggestionValue object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Entity(object): """ Entity. :attr str entity_name: The name of the entity. :attr datetime created: (optional) The timestamp for creation of the entity. :attr datetime updated: (optional) The timestamp for the last update to the entity. :attr str description: (optional) The description of the entity. :attr object metadata: (optional) Any metadata related to the entity. :attr bool fuzzy_match: (optional) Whether fuzzy matching is used for the entity. """ def __init__(self, entity_name, created=None, updated=None, description=None, metadata=None, fuzzy_match=None): """ Initialize a Entity object. :param str entity_name: The name of the entity. :param datetime created: (optional) The timestamp for creation of the entity. :param datetime updated: (optional) The timestamp for the last update to the entity. :param str description: (optional) The description of the entity. :param object metadata: (optional) Any metadata related to the entity. :param bool fuzzy_match: (optional) Whether fuzzy matching is used for the entity. """ self.entity_name = entity_name self.created = created self.updated = updated self.description = description self.metadata = metadata self.fuzzy_match = fuzzy_match @classmethod def _from_dict(cls, _dict): """Initialize a Entity object from a json dictionary.""" args = {} if 'entity' in _dict or 'entity_name' in _dict: args[ 'entity_name'] = _dict.get('entity') or _dict.get('entity_name') else: raise ValueError( 'Required property \'entity\' not present in Entity JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'description' in _dict: args['description'] = _dict.get('description') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'fuzzy_match' in _dict: args['fuzzy_match'] = _dict.get('fuzzy_match') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entity_name') and self.entity_name is not None: _dict['entity'] = self.entity_name if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'fuzzy_match') and self.fuzzy_match is not None: _dict['fuzzy_match'] = self.fuzzy_match return _dict def __str__(self): """Return a `str` version of this Entity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EntityCollection(object): """ An array of entities. :attr list[EntityExport] entities: An array of objects describing the entities defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, entities, pagination): """ Initialize a EntityCollection object. :param list[EntityExport] entities: An array of objects describing the entities defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ self.entities = entities self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a EntityCollection object from a json dictionary.""" args = {} if 'entities' in _dict: args['entities'] = [ EntityExport._from_dict(x) for x in (_dict.get('entities')) ] else: raise ValueError( 'Required property \'entities\' not present in EntityCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in EntityCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this EntityCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EntityExport(object): """ EntityExport. :attr str entity_name: The name of the entity. :attr datetime created: (optional) The timestamp for creation of the entity. :attr datetime updated: (optional) The timestamp for the last update to the entity. :attr str description: (optional) The description of the entity. :attr object metadata: (optional) Any metadata related to the entity. :attr bool fuzzy_match: (optional) Whether fuzzy matching is used for the entity. :attr list[ValueExport] values: (optional) An array objects describing the entity values. """ def __init__(self, entity_name, created=None, updated=None, description=None, metadata=None, fuzzy_match=None, values=None): """ Initialize a EntityExport object. :param str entity_name: The name of the entity. :param datetime created: (optional) The timestamp for creation of the entity. :param datetime updated: (optional) The timestamp for the last update to the entity. :param str description: (optional) The description of the entity. :param object metadata: (optional) Any metadata related to the entity. :param bool fuzzy_match: (optional) Whether fuzzy matching is used for the entity. :param list[ValueExport] values: (optional) An array objects describing the entity values. """ self.entity_name = entity_name self.created = created self.updated = updated self.description = description self.metadata = metadata self.fuzzy_match = fuzzy_match self.values = values @classmethod def _from_dict(cls, _dict): """Initialize a EntityExport object from a json dictionary.""" args = {} if 'entity' in _dict or 'entity_name' in _dict: args[ 'entity_name'] = _dict.get('entity') or _dict.get('entity_name') else: raise ValueError( 'Required property \'entity\' not present in EntityExport JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'description' in _dict: args['description'] = _dict.get('description') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'fuzzy_match' in _dict: args['fuzzy_match'] = _dict.get('fuzzy_match') if 'values' in _dict: args['values'] = [ ValueExport._from_dict(x) for x in (_dict.get('values')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entity_name') and self.entity_name is not None: _dict['entity'] = self.entity_name if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'fuzzy_match') and self.fuzzy_match is not None: _dict['fuzzy_match'] = self.fuzzy_match if hasattr(self, 'values') and self.values is not None: _dict['values'] = [x._to_dict() for x in self.values] return _dict def __str__(self): """Return a `str` version of this EntityExport object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EntityMention(object): """ An object describing a contextual entity mention. :attr str example_text: The text of the user input example. :attr str intent_name: The name of the intent. :attr list[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ def __init__(self, example_text, intent_name, location): """ Initialize a EntityMention object. :param str example_text: The text of the user input example. :param str intent_name: The name of the intent. :param list[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ self.example_text = example_text self.intent_name = intent_name self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a EntityMention object from a json dictionary.""" args = {} if 'text' in _dict or 'example_text' in _dict: args[ 'example_text'] = _dict.get('text') or _dict.get('example_text') else: raise ValueError( 'Required property \'text\' not present in EntityMention JSON') if 'intent' in _dict or 'intent_name' in _dict: args[ 'intent_name'] = _dict.get('intent') or _dict.get('intent_name') else: raise ValueError( 'Required property \'intent\' not present in EntityMention JSON' ) if 'location' in _dict: args['location'] = _dict.get('location') else: raise ValueError( 'Required property \'location\' not present in EntityMention JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'example_text') and self.example_text is not None: _dict['text'] = self.example_text if hasattr(self, 'intent_name') and self.intent_name is not None: _dict['intent'] = self.intent_name if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location return _dict def __str__(self): """Return a `str` version of this EntityMention object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class EntityMentionCollection(object): """ EntityMentionCollection. :attr list[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, examples, pagination): """ Initialize a EntityMentionCollection object. :param list[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :param Pagination pagination: The pagination data for the returned objects. """ self.examples = examples self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} if 'examples' in _dict: args['examples'] = [ EntityMention._from_dict(x) for x in (_dict.get('examples')) ] else: raise ValueError( 'Required property \'examples\' not present in EntityMentionCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in EntityMentionCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this EntityMentionCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Example(object): """ Example. :attr str example_text: The text of the user input example. :attr datetime created: (optional) The timestamp for creation of the example. :attr datetime updated: (optional) The timestamp for the last update to the example. :attr list[Mentions] mentions: (optional) An array of contextual entity mentions. """ def __init__(self, example_text, created=None, updated=None, mentions=None): """ Initialize a Example object. :param str example_text: The text of the user input example. :param datetime created: (optional) The timestamp for creation of the example. :param datetime updated: (optional) The timestamp for the last update to the example. :param list[Mentions] mentions: (optional) An array of contextual entity mentions. """ self.example_text = example_text self.created = created self.updated = updated self.mentions = mentions @classmethod def _from_dict(cls, _dict): """Initialize a Example object from a json dictionary.""" args = {} if 'text' in _dict or 'example_text' in _dict: args[ 'example_text'] = _dict.get('text') or _dict.get('example_text') else: raise ValueError( 'Required property \'text\' not present in Example JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'mentions' in _dict: args['mentions'] = [ Mentions._from_dict(x) for x in (_dict.get('mentions')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'example_text') and self.example_text is not None: _dict['text'] = self.example_text if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'mentions') and self.mentions is not None: _dict['mentions'] = [x._to_dict() for x in self.mentions] return _dict def __str__(self): """Return a `str` version of this Example object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ExampleCollection(object): """ ExampleCollection. :attr list[Example] examples: An array of objects describing the examples defined for the intent. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, examples, pagination): """ Initialize a ExampleCollection object. :param list[Example] examples: An array of objects describing the examples defined for the intent. :param Pagination pagination: The pagination data for the returned objects. """ self.examples = examples self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a ExampleCollection object from a json dictionary.""" args = {} if 'examples' in _dict: args['examples'] = [ Example._from_dict(x) for x in (_dict.get('examples')) ] else: raise ValueError( 'Required property \'examples\' not present in ExampleCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in ExampleCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this ExampleCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class InputData(object): """ An input object that includes the input text. :attr str text: The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. """ def __init__(self, text, **kwargs): """ Initialize a InputData object. :param str text: The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. :param **kwargs: (optional) Any additional properties. """ self.text = text for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a InputData object from a json dictionary.""" args = {} xtra = _dict.copy() if 'text' in _dict: args['text'] = _dict.get('text') del xtra['text'] else: raise ValueError( 'Required property \'text\' not present in InputData JSON') args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {'text'} if not hasattr(self, '_additionalProperties'): super(InputData, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(InputData, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this InputData object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Intent(object): """ Intent. :attr str intent_name: The name of the intent. :attr datetime created: (optional) The timestamp for creation of the intent. :attr datetime updated: (optional) The timestamp for the last update to the intent. :attr str description: (optional) The description of the intent. """ def __init__(self, intent_name, created=None, updated=None, description=None): """ Initialize a Intent object. :param str intent_name: The name of the intent. :param datetime created: (optional) The timestamp for creation of the intent. :param datetime updated: (optional) The timestamp for the last update to the intent. :param str description: (optional) The description of the intent. """ self.intent_name = intent_name self.created = created self.updated = updated self.description = description @classmethod def _from_dict(cls, _dict): """Initialize a Intent object from a json dictionary.""" args = {} if 'intent' in _dict or 'intent_name' in _dict: args[ 'intent_name'] = _dict.get('intent') or _dict.get('intent_name') else: raise ValueError( 'Required property \'intent\' not present in Intent JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'description' in _dict: args['description'] = _dict.get('description') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intent_name') and self.intent_name is not None: _dict['intent'] = self.intent_name if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict def __str__(self): """Return a `str` version of this Intent object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IntentCollection(object): """ IntentCollection. :attr list[IntentExport] intents: An array of objects describing the intents defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, intents, pagination): """ Initialize a IntentCollection object. :param list[IntentExport] intents: An array of objects describing the intents defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ self.intents = intents self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a IntentCollection object from a json dictionary.""" args = {} if 'intents' in _dict: args['intents'] = [ IntentExport._from_dict(x) for x in (_dict.get('intents')) ] else: raise ValueError( 'Required property \'intents\' not present in IntentCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in IntentCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this IntentCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class IntentExport(object): """ IntentExport. :attr str intent_name: The name of the intent. :attr datetime created: (optional) The timestamp for creation of the intent. :attr datetime updated: (optional) The timestamp for the last update to the intent. :attr str description: (optional) The description of the intent. :attr list[Example] examples: (optional) An array of objects describing the user input examples for the intent. """ def __init__(self, intent_name, created=None, updated=None, description=None, examples=None): """ Initialize a IntentExport object. :param str intent_name: The name of the intent. :param datetime created: (optional) The timestamp for creation of the intent. :param datetime updated: (optional) The timestamp for the last update to the intent. :param str description: (optional) The description of the intent. :param list[Example] examples: (optional) An array of objects describing the user input examples for the intent. """ self.intent_name = intent_name self.created = created self.updated = updated self.description = description self.examples = examples @classmethod def _from_dict(cls, _dict): """Initialize a IntentExport object from a json dictionary.""" args = {} if 'intent' in _dict or 'intent_name' in _dict: args[ 'intent_name'] = _dict.get('intent') or _dict.get('intent_name') else: raise ValueError( 'Required property \'intent\' not present in IntentExport JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'description' in _dict: args['description'] = _dict.get('description') if 'examples' in _dict: args['examples'] = [ Example._from_dict(x) for x in (_dict.get('examples')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intent_name') and self.intent_name is not None: _dict['intent'] = self.intent_name if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict def __str__(self): """Return a `str` version of this IntentExport object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogCollection(object): """ LogCollection. :attr list[LogExport] logs: An array of objects describing log events. :attr LogPagination pagination: The pagination data for the returned objects. """ def __init__(self, logs, pagination): """ Initialize a LogCollection object. :param list[LogExport] 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): """Initialize a LogCollection object from a json dictionary.""" args = {} if 'logs' in _dict: args['logs'] = [ LogExport._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) def _to_dict(self): """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 __str__(self): """Return a `str` version of this LogCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogExport(object): """ LogExport. :attr MessageRequest request: A request sent to the workspace, including the user input and context. :attr MessageResponse response: The response sent by the workspace, including the output text, detected intents and entities, and context. :attr str log_id: A unique identifier for the logged event. :attr str request_timestamp: The timestamp for receipt of the message. :attr str response_timestamp: The timestamp for the system response to the message. :attr str workspace_id: The unique identifier of the workspace where the request was made. :attr str language: The language of the workspace where the message request was made. """ def __init__(self, request, response, log_id, request_timestamp, response_timestamp, workspace_id, language): """ Initialize a LogExport object. :param MessageRequest request: A request sent to the workspace, including the user input and context. :param MessageResponse response: The response sent by the workspace, including the output text, detected intents and entities, and context. :param str log_id: A unique identifier for the logged event. :param str request_timestamp: The timestamp for receipt of the message. :param str response_timestamp: The timestamp for the system response to the message. :param str workspace_id: The unique identifier of the workspace where the request was made. :param str language: The language of the workspace where the message request was made. """ self.request = request self.response = response self.log_id = log_id self.request_timestamp = request_timestamp self.response_timestamp = response_timestamp self.workspace_id = workspace_id self.language = language @classmethod def _from_dict(cls, _dict): """Initialize a LogExport object from a json dictionary.""" args = {} if 'request' in _dict: args['request'] = MessageRequest._from_dict(_dict.get('request')) else: raise ValueError( 'Required property \'request\' not present in LogExport JSON') if 'response' in _dict: args['response'] = MessageResponse._from_dict(_dict.get('response')) else: raise ValueError( 'Required property \'response\' not present in LogExport JSON') if 'log_id' in _dict: args['log_id'] = _dict.get('log_id') else: raise ValueError( 'Required property \'log_id\' not present in LogExport JSON') if 'request_timestamp' in _dict: args['request_timestamp'] = _dict.get('request_timestamp') else: raise ValueError( 'Required property \'request_timestamp\' not present in LogExport JSON' ) if 'response_timestamp' in _dict: args['response_timestamp'] = _dict.get('response_timestamp') else: raise ValueError( 'Required property \'response_timestamp\' not present in LogExport JSON' ) if 'workspace_id' in _dict: args['workspace_id'] = _dict.get('workspace_id') else: raise ValueError( 'Required property \'workspace_id\' not present in LogExport JSON' ) if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in LogExport JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'request') and self.request is not None: _dict['request'] = self.request._to_dict() if hasattr(self, 'response') and self.response is not None: _dict['response'] = self.response._to_dict() if hasattr(self, 'log_id') and self.log_id is not None: _dict['log_id'] = self.log_id if hasattr(self, '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, 'workspace_id') and self.workspace_id is not None: _dict['workspace_id'] = self.workspace_id if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language return _dict def __str__(self): """Return a `str` version of this LogExport object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogMessage(object): """ Log message details. :attr str level: The severity of the log message. :attr str msg: The text of the log message. """ def __init__(self, level, msg, **kwargs): """ Initialize a LogMessage object. :param str level: The severity of the log message. :param str msg: The text of the log message. :param **kwargs: (optional) Any additional properties. """ self.level = level self.msg = msg for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a LogMessage object from a json dictionary.""" args = {} xtra = _dict.copy() if 'level' in _dict: args['level'] = _dict.get('level') del xtra['level'] else: raise ValueError( 'Required property \'level\' not present in LogMessage JSON') if 'msg' in _dict: args['msg'] = _dict.get('msg') del xtra['msg'] else: raise ValueError( 'Required property \'msg\' not present in LogMessage JSON') args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'level') and self.level is not None: _dict['level'] = self.level if hasattr(self, 'msg') and self.msg is not None: _dict['msg'] = self.msg if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {'level', 'msg'} if not hasattr(self, '_additionalProperties'): super(LogMessage, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(LogMessage, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this LogMessage object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class LogPagination(object): """ The pagination data for the returned objects. :attr str next_url: (optional) The URL that will return the next page of results, if any. :attr int matched: (optional) Reserved for future use. :attr str next_cursor: (optional) A token identifying the next page of results. """ def __init__(self, next_url=None, matched=None, next_cursor=None): """ 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): """Initialize a LogPagination object from a json dictionary.""" args = {} if 'next_url' in _dict: args['next_url'] = _dict.get('next_url') if 'matched' in _dict: args['matched'] = _dict.get('matched') if 'next_cursor' in _dict: args['next_cursor'] = _dict.get('next_cursor') return cls(**args) def _to_dict(self): """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 __str__(self): """Return a `str` version of this LogPagination object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Mentions(object): """ A mention of a contextual entity. :attr str entity: The name of the entity. :attr list[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ def __init__(self, entity, location): """ Initialize a Mentions object. :param str entity: The name of the entity. :param list[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ self.entity = entity self.location = location @classmethod def _from_dict(cls, _dict): """Initialize a Mentions object from a json dictionary.""" args = {} if 'entity' in _dict: args['entity'] = _dict.get('entity') else: raise ValueError( 'Required property \'entity\' not present in Mentions JSON') if 'location' in _dict: args['location'] = _dict.get('location') else: raise ValueError( 'Required property \'location\' not present in Mentions JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entity') and self.entity is not None: _dict['entity'] = self.entity if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location return _dict def __str__(self): """Return a `str` version of this Mentions object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageContextMetadata(object): """ Metadata related to the message. :attr str deployment: (optional) A label identifying the deployment environment, used for filtering log data. This string cannot contain carriage return, newline, or tab characters. :attr str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For Plus and Premium plans, this user ID is used to identify unique users for billing purposes. This string cannot contain carriage return, newline, or tab characters. """ def __init__(self, deployment=None, user_id=None): """ Initialize a MessageContextMetadata object. :param str deployment: (optional) A label identifying the deployment environment, used for filtering log data. This string cannot contain carriage return, newline, or tab characters. :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For Plus and Premium plans, this user ID is used to identify unique users for billing purposes. This string cannot contain carriage return, newline, or tab characters. """ self.deployment = deployment self.user_id = user_id @classmethod def _from_dict(cls, _dict): """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} if 'deployment' in _dict: args['deployment'] = _dict.get('deployment') if 'user_id' in _dict: args['user_id'] = _dict.get('user_id') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'deployment') and self.deployment is not None: _dict['deployment'] = self.deployment if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict def __str__(self): """Return a `str` version of this MessageContextMetadata object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageInput(object): """ The text of the user input. :attr str text: (optional) The user's input. """ def __init__(self, text=None): """ Initialize a MessageInput object. :param str text: (optional) The user's input. """ self.text = text @classmethod def _from_dict(cls, _dict): """Initialize a MessageInput object from a json dictionary.""" args = {} if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict def __str__(self): """Return a `str` version of this MessageInput object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageRequest(object): """ A request sent to the workspace, including the user input and context. :attr InputData input: (optional) An input object that includes the input text. :attr bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. :attr Context context: (optional) State information for the conversation. To maintain state, include the context from the previous response. :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. :attr OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. """ def __init__(self, input=None, alternate_intents=None, context=None, entities=None, intents=None, output=None): """ Initialize a MessageRequest object. :param InputData input: (optional) An input object that includes the input text. :param bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. :param Context context: (optional) State information for the conversation. To maintain state, include the context from the previous response. :param list[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :param list[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. """ self.input = input self.alternate_intents = alternate_intents self.context = context self.entities = entities self.intents = intents self.output = output @classmethod def _from_dict(cls, _dict): """Initialize a MessageRequest object from a json dictionary.""" args = {} if 'input' in _dict: args['input'] = InputData._from_dict(_dict.get('input')) if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') if 'context' in _dict: args['context'] = Context._from_dict(_dict.get('context')) if 'entities' in _dict: args['entities'] = [ RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) ] if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'output' in _dict: args['output'] = OutputData._from_dict(_dict.get('output')) return cls(**args) def _to_dict(self): """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, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context._to_dict() if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output._to_dict() return _dict def __str__(self): """Return a `str` version of this MessageRequest object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MessageResponse(object): """ The response sent by the workspace, including the output text, detected intents and entities, and context. :attr MessageInput input: (optional) The text of the user input. :attr list[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. :attr list[RuntimeEntity] entities: An array of entities identified in the user input. :attr bool alternate_intents: (optional) Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. :attr Context context: State information for the conversation. To maintain state, include the context from the previous response. :attr OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. :attr list[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ def __init__(self, intents, entities, context, output, input=None, alternate_intents=None, actions=None): """ Initialize a MessageResponse object. :param list[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. :param list[RuntimeEntity] entities: An array of entities identified in the user input. :param Context context: State information for the conversation. To maintain state, include the context from the previous response. :param OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. :param MessageInput input: (optional) The text of the user input. :param bool alternate_intents: (optional) Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. :param list[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ self.input = input self.intents = intents self.entities = entities self.alternate_intents = alternate_intents self.context = context self.output = output self.actions = actions @classmethod def _from_dict(cls, _dict): """Initialize a MessageResponse object from a json dictionary.""" args = {} if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] else: raise ValueError( 'Required property \'intents\' not present in MessageResponse JSON' ) if 'entities' in _dict: args['entities'] = [ RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) ] else: raise ValueError( 'Required property \'entities\' not present in MessageResponse JSON' ) if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') if 'context' in _dict: args['context'] = Context._from_dict(_dict.get('context')) else: raise ValueError( 'Required property \'context\' not present in MessageResponse JSON' ) if 'output' in _dict: args['output'] = OutputData._from_dict(_dict.get('output')) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) if 'actions' in _dict: args['actions'] = [ DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: _dict['input'] = self.input._to_dict() if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context._to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output._to_dict() if hasattr(self, 'actions') and self.actions is not None: _dict['actions'] = [x._to_dict() for x in self.actions] return _dict def __str__(self): """Return a `str` version of this MessageResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class OutputData(object): """ An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. :attr list[LogMessage] log_messages: An array of up to 50 messages logged with the request. :attr list[str] text: An array of responses to the user. :attr list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. :attr list[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. :attr list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. """ def __init__(self, log_messages, text, generic=None, nodes_visited=None, nodes_visited_details=None, **kwargs): """ Initialize a OutputData object. :param list[LogMessage] log_messages: An array of up to 50 messages logged with the request. :param list[str] text: An array of responses to the user. :param list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. :param list[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. :param **kwargs: (optional) Any additional properties. """ self.log_messages = log_messages self.text = text self.generic = generic self.nodes_visited = nodes_visited self.nodes_visited_details = nodes_visited_details for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a OutputData object from a json dictionary.""" args = {} xtra = _dict.copy() if 'log_messages' in _dict: args['log_messages'] = [ LogMessage._from_dict(x) for x in (_dict.get('log_messages')) ] del xtra['log_messages'] else: raise ValueError( 'Required property \'log_messages\' not present in OutputData JSON' ) if 'text' in _dict: args['text'] = _dict.get('text') del xtra['text'] else: raise ValueError( 'Required property \'text\' not present in OutputData JSON') if 'generic' in _dict: args['generic'] = [ DialogRuntimeResponseGeneric._from_dict(x) for x in (_dict.get('generic')) ] del xtra['generic'] if 'nodes_visited' in _dict: args['nodes_visited'] = _dict.get('nodes_visited') del xtra['nodes_visited'] if 'nodes_visited_details' in _dict: args['nodes_visited_details'] = [ DialogNodeVisitedDetails._from_dict(x) for x in (_dict.get('nodes_visited_details')) ] del xtra['nodes_visited_details'] args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'log_messages') and self.log_messages is not None: _dict['log_messages'] = [x._to_dict() for x in self.log_messages] if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'generic') and self.generic is not None: _dict['generic'] = [x._to_dict() for x in self.generic] if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: _dict['nodes_visited'] = self.nodes_visited if hasattr(self, 'nodes_visited_details' ) and self.nodes_visited_details is not None: _dict['nodes_visited_details'] = [ x._to_dict() for x in self.nodes_visited_details ] if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = { 'log_messages', 'text', 'generic', 'nodes_visited', 'nodes_visited_details' } if not hasattr(self, '_additionalProperties'): super(OutputData, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(OutputData, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this OutputData object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Pagination(object): """ The pagination data for the returned objects. :attr str refresh_url: The URL that will return the same page of results. :attr str next_url: (optional) The URL that will return the next page of results. :attr int total: (optional) Reserved for future use. :attr int matched: (optional) Reserved for future use. :attr str refresh_cursor: (optional) A token identifying the current page of results. :attr str next_cursor: (optional) A token identifying the next page of results. """ def __init__(self, refresh_url, next_url=None, total=None, matched=None, refresh_cursor=None, next_cursor=None): """ Initialize a Pagination object. :param str refresh_url: The URL that will return the same page of results. :param str next_url: (optional) The URL that will return the next page of results. :param int total: (optional) Reserved for future use. :param int matched: (optional) Reserved for future use. :param str refresh_cursor: (optional) A token identifying the current page of results. :param str next_cursor: (optional) A token identifying the next page of results. """ self.refresh_url = refresh_url self.next_url = next_url self.total = total self.matched = matched self.refresh_cursor = refresh_cursor self.next_cursor = next_cursor @classmethod def _from_dict(cls, _dict): """Initialize a Pagination object from a json dictionary.""" args = {} if 'refresh_url' in _dict: args['refresh_url'] = _dict.get('refresh_url') else: raise ValueError( 'Required property \'refresh_url\' not present in Pagination JSON' ) if 'next_url' in _dict: args['next_url'] = _dict.get('next_url') if 'total' in _dict: args['total'] = _dict.get('total') if 'matched' in _dict: args['matched'] = _dict.get('matched') if 'refresh_cursor' in _dict: args['refresh_cursor'] = _dict.get('refresh_cursor') if 'next_cursor' in _dict: args['next_cursor'] = _dict.get('next_cursor') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'refresh_url') and self.refresh_url is not None: _dict['refresh_url'] = self.refresh_url if hasattr(self, 'next_url') and self.next_url is not None: _dict['next_url'] = self.next_url if hasattr(self, 'total') and self.total is not None: _dict['total'] = self.total if hasattr(self, 'matched') and self.matched is not None: _dict['matched'] = self.matched if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: _dict['refresh_cursor'] = self.refresh_cursor if hasattr(self, 'next_cursor') and self.next_cursor is not None: _dict['next_cursor'] = self.next_cursor return _dict def __str__(self): """Return a `str` version of this Pagination object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RuntimeEntity(object): """ A term from the request that was identified as an entity. :attr str entity: An entity detected in the input. :attr list[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :attr str value: The term in the input text that was recognized as an entity value. :attr float confidence: (optional) A decimal percentage that represents Watson's confidence in the entity. :attr object metadata: (optional) Any metadata for the entity. :attr list[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ def __init__(self, entity, location, value, confidence=None, metadata=None, groups=None, **kwargs): """ Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. :param list[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :param str value: The term in the input text that was recognized as an entity value. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the entity. :param object metadata: (optional) Any metadata for the entity. :param list[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param **kwargs: (optional) Any additional properties. """ self.entity = entity self.location = location self.value = value self.confidence = confidence self.metadata = metadata self.groups = groups for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a RuntimeEntity object from a json dictionary.""" args = {} xtra = _dict.copy() if 'entity' in _dict: args['entity'] = _dict.get('entity') del xtra['entity'] else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) if 'location' in _dict: args['location'] = _dict.get('location') del xtra['location'] else: raise ValueError( 'Required property \'location\' not present in RuntimeEntity JSON' ) if 'value' in _dict: args['value'] = _dict.get('value') del xtra['value'] else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') del xtra['confidence'] if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') del xtra['metadata'] if 'groups' in _dict: args['groups'] = [ CaptureGroup._from_dict(x) for x in (_dict.get('groups')) ] del xtra['groups'] args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entity') and self.entity is not None: _dict['entity'] = self.entity if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'groups') and self.groups is not None: _dict['groups'] = [x._to_dict() for x in self.groups] if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = { 'entity', 'location', 'value', 'confidence', 'metadata', 'groups' } if not hasattr(self, '_additionalProperties'): super(RuntimeEntity, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(RuntimeEntity, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this RuntimeEntity object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class RuntimeIntent(object): """ An intent identified in the user input. :attr str intent: The name of the recognized intent. :attr float confidence: A decimal percentage that represents Watson's confidence in the intent. """ def __init__(self, intent, confidence, **kwargs): """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. :param float confidence: A decimal percentage that represents Watson's confidence in the intent. :param **kwargs: (optional) Any additional properties. """ self.intent = intent self.confidence = confidence for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a RuntimeIntent object from a json dictionary.""" args = {} xtra = _dict.copy() if 'intent' in _dict: args['intent'] = _dict.get('intent') del xtra['intent'] else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') del xtra['confidence'] else: raise ValueError( 'Required property \'confidence\' not present in RuntimeIntent JSON' ) args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intent') and self.intent is not None: _dict['intent'] = self.intent if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {'intent', 'confidence'} if not hasattr(self, '_additionalProperties'): super(RuntimeIntent, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(RuntimeIntent, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this RuntimeIntent object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Synonym(object): """ Synonym. :attr str synonym_text: The text of the synonym. :attr datetime created: (optional) The timestamp for creation of the synonym. :attr datetime updated: (optional) The timestamp for the most recent update to the synonym. """ def __init__(self, synonym_text, created=None, updated=None): """ Initialize a Synonym object. :param str synonym_text: The text of the synonym. :param datetime created: (optional) The timestamp for creation of the synonym. :param datetime updated: (optional) The timestamp for the most recent update to the synonym. """ self.synonym_text = synonym_text self.created = created self.updated = updated @classmethod def _from_dict(cls, _dict): """Initialize a Synonym object from a json dictionary.""" args = {} if 'synonym' in _dict or 'synonym_text' in _dict: args['synonym_text'] = _dict.get('synonym') or _dict.get( 'synonym_text') else: raise ValueError( 'Required property \'synonym\' not present in Synonym JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'synonym_text') and self.synonym_text is not None: _dict['synonym'] = self.synonym_text if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) return _dict def __str__(self): """Return a `str` version of this Synonym object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SynonymCollection(object): """ SynonymCollection. :attr list[Synonym] synonyms: An array of synonyms. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, synonyms, pagination): """ Initialize a SynonymCollection object. :param list[Synonym] synonyms: An array of synonyms. :param Pagination pagination: The pagination data for the returned objects. """ self.synonyms = synonyms self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a SynonymCollection object from a json dictionary.""" args = {} if 'synonyms' in _dict: args['synonyms'] = [ Synonym._from_dict(x) for x in (_dict.get('synonyms')) ] else: raise ValueError( 'Required property \'synonyms\' not present in SynonymCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in SynonymCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'synonyms') and self.synonyms is not None: _dict['synonyms'] = [x._to_dict() for x in self.synonyms] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this SynonymCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class SystemResponse(object): """ For internal use only. """ def __init__(self, **kwargs): """ Initialize a SystemResponse object. :param **kwargs: (optional) Any additional properties. """ for _key, _value in kwargs.items(): setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a SystemResponse object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) if _value is not None: _dict[_key] = _value return _dict def __setattr__(self, name, value): properties = {} if not hasattr(self, '_additionalProperties'): super(SystemResponse, self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(SystemResponse, self).__setattr__(name, value) def __str__(self): """Return a `str` version of this SystemResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Value(object): """ Value. :attr str value_text: The text of the entity value. :attr object metadata: (optional) Any metadata related to the entity value. :attr datetime created: (optional) The timestamp for creation of the entity value. :attr datetime updated: (optional) The timestamp for the last update to the entity value. :attr list[str] synonyms: (optional) An array containing any synonyms for the entity value. :attr list[str] patterns: (optional) An array containing any patterns for the entity value. :attr str value_type: Specifies the type of value. """ def __init__(self, value_text, value_type, metadata=None, created=None, updated=None, synonyms=None, patterns=None): """ Initialize a Value object. :param str value_text: The text of the entity value. :param str value_type: Specifies the type of value. :param object metadata: (optional) Any metadata related to the entity value. :param datetime created: (optional) The timestamp for creation of the entity value. :param datetime updated: (optional) The timestamp for the last update to the entity value. :param list[str] synonyms: (optional) An array containing any synonyms for the entity value. :param list[str] patterns: (optional) An array containing any patterns for the entity value. """ self.value_text = value_text self.metadata = metadata self.created = created self.updated = updated self.synonyms = synonyms self.patterns = patterns self.value_type = value_type @classmethod def _from_dict(cls, _dict): """Initialize a Value object from a json dictionary.""" args = {} if 'value' in _dict or 'value_text' in _dict: args['value_text'] = _dict.get('value') or _dict.get('value_text') else: raise ValueError( 'Required property \'value\' not present in Value JSON') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'synonyms' in _dict: args['synonyms'] = _dict.get('synonyms') if 'patterns' in _dict: args['patterns'] = _dict.get('patterns') if 'type' in _dict or 'value_type' in _dict: args['value_type'] = _dict.get('type') or _dict.get('value_type') else: raise ValueError( 'Required property \'type\' not present in Value JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'value_text') and self.value_text is not None: _dict['value'] = self.value_text if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'synonyms') and self.synonyms is not None: _dict['synonyms'] = self.synonyms if hasattr(self, 'patterns') and self.patterns is not None: _dict['patterns'] = self.patterns if hasattr(self, 'value_type') and self.value_type is not None: _dict['type'] = self.value_type return _dict def __str__(self): """Return a `str` version of this Value object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ValueCollection(object): """ ValueCollection. :attr list[ValueExport] values: An array of entity values. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, values, pagination): """ Initialize a ValueCollection object. :param list[ValueExport] values: An array of entity values. :param Pagination pagination: The pagination data for the returned objects. """ self.values = values self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a ValueCollection object from a json dictionary.""" args = {} if 'values' in _dict: args['values'] = [ ValueExport._from_dict(x) for x in (_dict.get('values')) ] else: raise ValueError( 'Required property \'values\' not present in ValueCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in ValueCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'values') and self.values is not None: _dict['values'] = [x._to_dict() for x in self.values] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this ValueCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ValueExport(object): """ ValueExport. :attr str value_text: The text of the entity value. :attr object metadata: (optional) Any metadata related to the entity value. :attr datetime created: (optional) The timestamp for creation of the entity value. :attr datetime updated: (optional) The timestamp for the last update to the entity value. :attr list[str] synonyms: (optional) An array containing any synonyms for the entity value. :attr list[str] patterns: (optional) An array containing any patterns for the entity value. :attr str value_type: Specifies the type of value. """ def __init__(self, value_text, value_type, metadata=None, created=None, updated=None, synonyms=None, patterns=None): """ Initialize a ValueExport object. :param str value_text: The text of the entity value. :param str value_type: Specifies the type of value. :param object metadata: (optional) Any metadata related to the entity value. :param datetime created: (optional) The timestamp for creation of the entity value. :param datetime updated: (optional) The timestamp for the last update to the entity value. :param list[str] synonyms: (optional) An array containing any synonyms for the entity value. :param list[str] patterns: (optional) An array containing any patterns for the entity value. """ self.value_text = value_text self.metadata = metadata self.created = created self.updated = updated self.synonyms = synonyms self.patterns = patterns self.value_type = value_type @classmethod def _from_dict(cls, _dict): """Initialize a ValueExport object from a json dictionary.""" args = {} if 'value' in _dict or 'value_text' in _dict: args['value_text'] = _dict.get('value') or _dict.get('value_text') else: raise ValueError( 'Required property \'value\' not present in ValueExport JSON') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'synonyms' in _dict: args['synonyms'] = _dict.get('synonyms') if 'patterns' in _dict: args['patterns'] = _dict.get('patterns') if 'type' in _dict or 'value_type' in _dict: args['value_type'] = _dict.get('type') or _dict.get('value_type') else: raise ValueError( 'Required property \'type\' not present in ValueExport JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'value_text') and self.value_text is not None: _dict['value'] = self.value_text if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'synonyms') and self.synonyms is not None: _dict['synonyms'] = self.synonyms if hasattr(self, 'patterns') and self.patterns is not None: _dict['patterns'] = self.patterns if hasattr(self, 'value_type') and self.value_type is not None: _dict['type'] = self.value_type return _dict def __str__(self): """Return a `str` version of this ValueExport object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Workspace(object): """ Workspace. :attr str name: The name of the workspace. :attr str language: The language of the workspace. :attr datetime created: (optional) The timestamp for creation of the workspace. :attr datetime updated: (optional) The timestamp for the last update to the workspace. :attr str workspace_id: The workspace ID of the workspace. :attr str description: (optional) The description of the workspace. :attr object metadata: (optional) Any metadata related to the workspace. :attr bool learning_opt_out: (optional) Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. :attr WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. """ def __init__(self, name, language, workspace_id, created=None, updated=None, description=None, metadata=None, learning_opt_out=None, system_settings=None): """ Initialize a Workspace object. :param str name: The name of the workspace. :param str language: The language of the workspace. :param str workspace_id: The workspace ID of the workspace. :param datetime created: (optional) The timestamp for creation of the workspace. :param datetime updated: (optional) The timestamp for the last update to the workspace. :param str description: (optional) The description of the workspace. :param object metadata: (optional) Any metadata related to the workspace. :param bool learning_opt_out: (optional) Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. """ self.name = name self.language = language self.created = created self.updated = updated self.workspace_id = workspace_id self.description = description self.metadata = metadata self.learning_opt_out = learning_opt_out self.system_settings = system_settings @classmethod def _from_dict(cls, _dict): """Initialize a Workspace object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Workspace JSON') if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in Workspace JSON') if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'workspace_id' in _dict: args['workspace_id'] = _dict.get('workspace_id') else: raise ValueError( 'Required property \'workspace_id\' not present in Workspace JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'learning_opt_out' in _dict: args['learning_opt_out'] = _dict.get('learning_opt_out') if 'system_settings' in _dict: args['system_settings'] = WorkspaceSystemSettings._from_dict( _dict.get('system_settings')) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'workspace_id') and self.workspace_id is not None: _dict['workspace_id'] = self.workspace_id if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'learning_opt_out') and self.learning_opt_out is not None: _dict['learning_opt_out'] = self.learning_opt_out if hasattr(self, 'system_settings') and self.system_settings is not None: _dict['system_settings'] = self.system_settings._to_dict() return _dict def __str__(self): """Return a `str` version of this Workspace object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WorkspaceCollection(object): """ WorkspaceCollection. :attr list[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :attr Pagination pagination: The pagination data for the returned objects. """ def __init__(self, workspaces, pagination): """ Initialize a WorkspaceCollection object. :param list[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :param Pagination pagination: The pagination data for the returned objects. """ self.workspaces = workspaces self.pagination = pagination @classmethod def _from_dict(cls, _dict): """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} if 'workspaces' in _dict: args['workspaces'] = [ Workspace._from_dict(x) for x in (_dict.get('workspaces')) ] else: raise ValueError( 'Required property \'workspaces\' not present in WorkspaceCollection JSON' ) if 'pagination' in _dict: args['pagination'] = Pagination._from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in WorkspaceCollection JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'workspaces') and self.workspaces is not None: _dict['workspaces'] = [x._to_dict() for x in self.workspaces] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination._to_dict() return _dict def __str__(self): """Return a `str` version of this WorkspaceCollection object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WorkspaceExport(object): """ WorkspaceExport. :attr str name: The name of the workspace. :attr str description: The description of the workspace. :attr str language: The language of the workspace. :attr object metadata: Any metadata that is required by the workspace. :attr datetime created: (optional) The timestamp for creation of the workspace. :attr datetime updated: (optional) The timestamp for the last update to the workspace. :attr str workspace_id: The workspace ID of the workspace. :attr str status: The current status of the workspace. :attr bool learning_opt_out: Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. :attr WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. :attr list[IntentExport] intents: (optional) An array of intents. :attr list[EntityExport] entities: (optional) An array of entities. :attr list[Counterexample] counterexamples: (optional) An array of counterexamples. :attr list[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. """ def __init__(self, name, description, language, metadata, workspace_id, status, learning_opt_out, created=None, updated=None, system_settings=None, intents=None, entities=None, counterexamples=None, dialog_nodes=None): """ Initialize a WorkspaceExport object. :param str name: The name of the workspace. :param str description: The description of the workspace. :param str language: The language of the workspace. :param object metadata: Any metadata that is required by the workspace. :param str workspace_id: The workspace ID of the workspace. :param str status: The current status of the workspace. :param bool learning_opt_out: Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. :param datetime created: (optional) The timestamp for creation of the workspace. :param datetime updated: (optional) The timestamp for the last update to the workspace. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. :param list[IntentExport] intents: (optional) An array of intents. :param list[EntityExport] entities: (optional) An array of entities. :param list[Counterexample] counterexamples: (optional) An array of counterexamples. :param list[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. """ self.name = name self.description = description self.language = language self.metadata = metadata self.created = created self.updated = updated self.workspace_id = workspace_id self.status = status self.learning_opt_out = learning_opt_out self.system_settings = system_settings self.intents = intents self.entities = entities self.counterexamples = counterexamples self.dialog_nodes = dialog_nodes @classmethod def _from_dict(cls, _dict): """Initialize a WorkspaceExport object from a json dictionary.""" args = {} if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in WorkspaceExport JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') else: raise ValueError( 'Required property \'description\' not present in WorkspaceExport JSON' ) if 'language' in _dict: args['language'] = _dict.get('language') else: raise ValueError( 'Required property \'language\' not present in WorkspaceExport JSON' ) if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') else: raise ValueError( 'Required property \'metadata\' not present in WorkspaceExport JSON' ) if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'workspace_id' in _dict: args['workspace_id'] = _dict.get('workspace_id') else: raise ValueError( 'Required property \'workspace_id\' not present in WorkspaceExport JSON' ) if 'status' in _dict: args['status'] = _dict.get('status') else: raise ValueError( 'Required property \'status\' not present in WorkspaceExport JSON' ) if 'learning_opt_out' in _dict: args['learning_opt_out'] = _dict.get('learning_opt_out') else: raise ValueError( 'Required property \'learning_opt_out\' not present in WorkspaceExport JSON' ) if 'system_settings' in _dict: args['system_settings'] = WorkspaceSystemSettings._from_dict( _dict.get('system_settings')) if 'intents' in _dict: args['intents'] = [ IntentExport._from_dict(x) for x in (_dict.get('intents')) ] if 'entities' in _dict: args['entities'] = [ EntityExport._from_dict(x) for x in (_dict.get('entities')) ] if 'counterexamples' in _dict: args['counterexamples'] = [ Counterexample._from_dict(x) for x in (_dict.get('counterexamples')) ] if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ DialogNode._from_dict(x) for x in (_dict.get('dialog_nodes')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'workspace_id') and self.workspace_id is not None: _dict['workspace_id'] = self.workspace_id if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'learning_opt_out') and self.learning_opt_out is not None: _dict['learning_opt_out'] = self.learning_opt_out if hasattr(self, 'system_settings') and self.system_settings is not None: _dict['system_settings'] = self.system_settings._to_dict() if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'counterexamples') and self.counterexamples is not None: _dict['counterexamples'] = [ x._to_dict() for x in self.counterexamples ] if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: _dict['dialog_nodes'] = [x._to_dict() for x in self.dialog_nodes] return _dict def __str__(self): """Return a `str` version of this WorkspaceExport object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WorkspaceSystemSettings(object): """ Global settings for the workspace. :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings related to the Watson Assistant tool. :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace settings related to the disambiguation feature. **Note:** This feature is available only to Premium users. :attr object human_agent_assist: (optional) For internal use only. """ def __init__(self, tooling=None, disambiguation=None, human_agent_assist=None): """ Initialize a WorkspaceSystemSettings object. :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings related to the Watson Assistant tool. :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace settings related to the disambiguation feature. **Note:** This feature is available only to Premium users. :param object human_agent_assist: (optional) For internal use only. """ self.tooling = tooling self.disambiguation = disambiguation self.human_agent_assist = human_agent_assist @classmethod def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} if 'tooling' in _dict: args['tooling'] = WorkspaceSystemSettingsTooling._from_dict( _dict.get('tooling')) if 'disambiguation' in _dict: args[ 'disambiguation'] = WorkspaceSystemSettingsDisambiguation._from_dict( _dict.get('disambiguation')) if 'human_agent_assist' in _dict: args['human_agent_assist'] = _dict.get('human_agent_assist') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tooling') and self.tooling is not None: _dict['tooling'] = self.tooling._to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: _dict['disambiguation'] = self.disambiguation._to_dict() if hasattr( self, 'human_agent_assist') and self.human_agent_assist is not None: _dict['human_agent_assist'] = self.human_agent_assist return _dict def __str__(self): """Return a `str` version of this WorkspaceSystemSettings object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WorkspaceSystemSettingsDisambiguation(object): """ Workspace settings related to the disambiguation feature. **Note:** This feature is available only to Premium users. :attr str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. :attr str none_of_the_above_prompt: (optional) The user-facing label for the option users can select if none of the suggested options is correct. If no value is specified for this property, this option does not appear. :attr bool enabled: (optional) Whether the disambiguation feature is enabled for the workspace. :attr str sensitivity: (optional) The sensitivity of the disambiguation feature to intent detection conflicts. Set to **high** if you want the disambiguation feature to be triggered more often. This can be useful for testing or demonstration purposes. """ def __init__(self, prompt=None, none_of_the_above_prompt=None, enabled=None, sensitivity=None): """ Initialize a WorkspaceSystemSettingsDisambiguation object. :param str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. :param str none_of_the_above_prompt: (optional) The user-facing label for the option users can select if none of the suggested options is correct. If no value is specified for this property, this option does not appear. :param bool enabled: (optional) Whether the disambiguation feature is enabled for the workspace. :param str sensitivity: (optional) The sensitivity of the disambiguation feature to intent detection conflicts. Set to **high** if you want the disambiguation feature to be triggered more often. This can be useful for testing or demonstration purposes. """ self.prompt = prompt self.none_of_the_above_prompt = none_of_the_above_prompt self.enabled = enabled self.sensitivity = sensitivity @classmethod def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} if 'prompt' in _dict: args['prompt'] = _dict.get('prompt') if 'none_of_the_above_prompt' in _dict: args['none_of_the_above_prompt'] = _dict.get( 'none_of_the_above_prompt') if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'sensitivity' in _dict: args['sensitivity'] = _dict.get('sensitivity') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'prompt') and self.prompt is not None: _dict['prompt'] = self.prompt if hasattr(self, 'none_of_the_above_prompt' ) and self.none_of_the_above_prompt is not None: _dict['none_of_the_above_prompt'] = self.none_of_the_above_prompt if hasattr(self, 'enabled') and self.enabled is not None: _dict['enabled'] = self.enabled if hasattr(self, 'sensitivity') and self.sensitivity is not None: _dict['sensitivity'] = self.sensitivity return _dict def __str__(self): """Return a `str` version of this WorkspaceSystemSettingsDisambiguation object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class WorkspaceSystemSettingsTooling(object): """ Workspace settings related to the Watson Assistant tool. :attr bool store_generic_responses: (optional) Whether the dialog JSON editor displays text responses within the `output.generic` object. """ def __init__(self, store_generic_responses=None): """ Initialize a WorkspaceSystemSettingsTooling object. :param bool store_generic_responses: (optional) Whether the dialog JSON editor displays text responses within the `output.generic` object. """ self.store_generic_responses = store_generic_responses @classmethod def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} if 'store_generic_responses' in _dict: args['store_generic_responses'] = _dict.get( 'store_generic_responses') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'store_generic_responses' ) and self.store_generic_responses is not None: _dict['store_generic_responses'] = self.store_generic_responses return _dict def __str__(self): """Return a `str` version of this WorkspaceSystemSettingsTooling object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/personality_insights_v3.py0000644000076500000240000014737613451412230031667 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ The IBM Watson™ Personality Insights service enables applications to derive insights from social media, enterprise data, or other digital communications. The service uses linguistic analytics to infer individuals' intrinsic personality characteristics, including Big Five, Needs, and Values, from digital communications such as email, text messages, tweets, and forum posts. The service can automatically infer, from potentially noisy social media, portraits of individuals that reflect their personality characteristics. The service can infer consumption preferences based on the results of its analysis and, for JSON content that is timestamped, can report temporal behavior. * For information about the meaning of the models that the service uses to describe personality characteristics, see [Personality models](https://cloud.ibm.com/docs/services/personality-insights/models.html). * For information about the meaning of the consumption preferences, see [Consumption preferences](https://cloud.ibm.com/docs/services/personality-insights/preferences.html). **Note:** Request logging is disabled for the Personality Insights service. Regardless of whether you set the `X-Watson-Learning-Opt-Out` request header, the service does not log or retain data from requests and responses. """ from __future__ import absolute_import import json from .watson_service import WatsonService from .utils import deprecated ############################################################################## # Service ############################################################################## @deprecated("watson-developer-cloud moved to ibm-watson. To get updates, use the new package.") class PersonalityInsightsV3(WatsonService): """The Personality Insights V3 service.""" default_url = 'https://gateway.watsonplatform.net/personality-insights/api' def __init__( self, version, url=default_url, username=None, password=None, iam_apikey=None, iam_access_token=None, iam_url=None, ): """ Construct a new client for the Personality Insights service. :param str version: The API version date to use with the service, in "YYYY-MM-DD" format. Whenever the API is changed in a backwards incompatible way, a new minor version of the API is released. The service uses the API version for the date you specify, or the most recent version before that date. Note that you should not programmatically specify the current date at runtime, in case the API has been updated since your application's release. Instead, specify a version date that is compatible with your application, and don't change it until your application is ready for a later version. :param str url: The base url to use when contacting the service (e.g. "https://gateway.watsonplatform.net/personality-insights/api"). The base url may differ between Bluemix regions. :param str username: The username used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str password: The password used to authenticate with the service. Username and password credentials are only required to run your application locally or outside of Bluemix. When running on Bluemix, the credentials will be automatically loaded from the `VCAP_SERVICES` environment variable. :param str iam_apikey: An API key that can be used to request IAM tokens. If this API key is provided, the SDK will manage the token and handle the refreshing. :param str iam_access_token: An IAM access token is fully managed by the application. Responsibility falls on the application to refresh the token, either before it expires or reactively upon receiving a 401 from the service as any requests made with an expired token will fail. :param str iam_url: An optional URL for the IAM service API. Defaults to 'https://iam.bluemix.net/identity/token'. """ WatsonService.__init__( self, vcap_services_name='personality_insights', url=url, username=username, password=password, iam_apikey=iam_apikey, iam_access_token=iam_access_token, iam_url=iam_url, use_vcap_services=True, display_name='Personality Insights') self.version = version ######################### # Methods ######################### def profile(self, content, content_type, accept=None, content_language=None, accept_language=None, raw_scores=None, csv_headers=None, consumption_preferences=None, **kwargs): """ Get profile. Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of input content, but it requires much less text to produce an accurate profile. The service can analyze text in Arabic, English, Japanese, Korean, or Spanish. It can return its results in a variety of languages. **See also:** * [Requesting a profile](https://cloud.ibm.com/docs/services/personality-insights/input.html) * [Providing sufficient input](https://cloud.ibm.com/docs/services/personality-insights/input.html#sufficient) ### Content types You can provide input content as plain text (`text/plain`), HTML (`text/html`), or JSON (`application/json`) by specifying the **Content-Type** parameter. The default is `text/plain`. * Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8. * Per the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text; for example, `Content-Type: text/plain;charset=utf-8`. **See also:** [Specifying request and response formats](https://cloud.ibm.com/docs/services/personality-insights/input.html#formats) ### Accept types You must request a response as JSON (`application/json`) or comma-separated values (`text/csv`) by specifying the **Accept** parameter. CSV output includes a fixed number of columns. Set the **csv_headers** parameter to `true` to request optional column headers for CSV output. **See also:** * [Understanding a JSON profile](https://cloud.ibm.com/docs/services/personality-insights/output.html) * [Understanding a CSV profile](https://cloud.ibm.com/docs/services/personality-insights/output-csv.html). :param Content content: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see [Providing sufficient input](https://cloud.ibm.com/docs/services/personality-insights/input.html#sufficient). For JSON input, provide an object of type `Content`. :param str accept: The type of the response. For more information, see **Accept types** in the method description. :param str content_type: The type of the input. For more information, see **Content types** in the method description. Default: `text/plain`. :param str content_language: The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The effect of the **Content-Language** parameter depends on the **Content-Type** parameter. When **Content-Type** is `text/plain` or `text/html`, **Content-Language** is the only way to specify the language. When **Content-Type** is `application/json`, **Content-Language** overrides a language specified with the `language` parameter of a `ContentItem` object, and content items that specify a different language are ignored; omit this parameter to base the language on the specification of the content items. You can specify any combination of languages for **Content-Language** and **Accept-Language**. :param str accept_language: The desired language of the response. For two-character arguments, regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can specify any combination of languages for the input and response content. :param bool raw_scores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw scores are not compared with a sample population. By default, only normalized percentiles are returned. :param bool csv_headers: Indicates whether column labels are returned with a CSV response. By default, no column labels are returned. Applies only when the response type is CSV (`text/csv`). :param bool consumption_preferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are returned. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ if content is None: raise ValueError('content must be provided') if content_type is None: raise ValueError('content_type must be provided') if isinstance(content, Content): content = self._convert_model(content, Content) headers = { 'Accept': accept, 'Content-Type': content_type, 'Content-Language': content_language, 'Accept-Language': accept_language } if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers[ 'X-IBMCloud-SDK-Analytics'] = 'service_name=personality_insights;service_version=V3;operation_id=profile' params = { 'version': self.version, 'raw_scores': raw_scores, 'csv_headers': csv_headers, 'consumption_preferences': consumption_preferences } if content_type == 'application/json' and isinstance(content, dict): data = json.dumps(content) else: data = content url = '/v3/profile' response = self.request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=(accept is None or accept == 'application/json')) return response ############################################################################## # Models ############################################################################## class Behavior(object): """ Behavior. :attr str trait_id: The unique, non-localized identifier of the characteristic to which the results pertain. IDs have the form `behavior_{value}`. :attr str name: The user-visible, localized name of the characteristic. :attr str category: The category of the characteristic: `behavior` for temporal data. :attr float percentage: For JSON content that is timestamped, the percentage of timestamped input data that occurred during that day of the week or hour of the day. The range is 0 to 1. """ def __init__(self, trait_id, name, category, percentage): """ Initialize a Behavior object. :param str trait_id: The unique, non-localized identifier of the characteristic to which the results pertain. IDs have the form `behavior_{value}`. :param str name: The user-visible, localized name of the characteristic. :param str category: The category of the characteristic: `behavior` for temporal data. :param float percentage: For JSON content that is timestamped, the percentage of timestamped input data that occurred during that day of the week or hour of the day. The range is 0 to 1. """ self.trait_id = trait_id self.name = name self.category = category self.percentage = percentage @classmethod def _from_dict(cls, _dict): """Initialize a Behavior object from a json dictionary.""" args = {} if 'trait_id' in _dict: args['trait_id'] = _dict.get('trait_id') else: raise ValueError( 'Required property \'trait_id\' not present in Behavior JSON') if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Behavior JSON') if 'category' in _dict: args['category'] = _dict.get('category') else: raise ValueError( 'Required property \'category\' not present in Behavior JSON') if 'percentage' in _dict: args['percentage'] = _dict.get('percentage') else: raise ValueError( 'Required property \'percentage\' not present in Behavior JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'trait_id') and self.trait_id is not None: _dict['trait_id'] = self.trait_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'category') and self.category is not None: _dict['category'] = self.category if hasattr(self, 'percentage') and self.percentage is not None: _dict['percentage'] = self.percentage return _dict def __str__(self): """Return a `str` version of this Behavior object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConsumptionPreferences(object): """ ConsumptionPreferences. :attr str consumption_preference_id: The unique, non-localized identifier of the consumption preference to which the results pertain. IDs have the form `consumption_preferences_{preference}`. :attr str name: The user-visible, localized name of the consumption preference. :attr float score: The score for the consumption preference: * `0.0`: Unlikely * `0.5`: Neutral * `1.0`: Likely The scores for some preferences are binary and do not allow a neutral value. The score is an indication of preference based on the results inferred from the input text, not a normalized percentile. """ def __init__(self, consumption_preference_id, name, score): """ Initialize a ConsumptionPreferences object. :param str consumption_preference_id: The unique, non-localized identifier of the consumption preference to which the results pertain. IDs have the form `consumption_preferences_{preference}`. :param str name: The user-visible, localized name of the consumption preference. :param float score: The score for the consumption preference: * `0.0`: Unlikely * `0.5`: Neutral * `1.0`: Likely The scores for some preferences are binary and do not allow a neutral value. The score is an indication of preference based on the results inferred from the input text, not a normalized percentile. """ self.consumption_preference_id = consumption_preference_id self.name = name self.score = score @classmethod def _from_dict(cls, _dict): """Initialize a ConsumptionPreferences object from a json dictionary.""" args = {} if 'consumption_preference_id' in _dict: args['consumption_preference_id'] = _dict.get( 'consumption_preference_id') else: raise ValueError( 'Required property \'consumption_preference_id\' not present in ConsumptionPreferences JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in ConsumptionPreferences JSON' ) if 'score' in _dict: args['score'] = _dict.get('score') else: raise ValueError( 'Required property \'score\' not present in ConsumptionPreferences JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'consumption_preference_id' ) and self.consumption_preference_id is not None: _dict['consumption_preference_id'] = self.consumption_preference_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict def __str__(self): """Return a `str` version of this ConsumptionPreferences object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConsumptionPreferencesCategory(object): """ ConsumptionPreferencesCategory. :attr str consumption_preference_category_id: The unique, non-localized identifier of the consumption preferences category to which the results pertain. IDs have the form `consumption_preferences_{category}`. :attr str name: The user-visible name of the consumption preferences category. :attr list[ConsumptionPreferences] consumption_preferences: Detailed results inferred from the input text for the individual preferences of the category. """ def __init__(self, consumption_preference_category_id, name, consumption_preferences): """ Initialize a ConsumptionPreferencesCategory object. :param str consumption_preference_category_id: The unique, non-localized identifier of the consumption preferences category to which the results pertain. IDs have the form `consumption_preferences_{category}`. :param str name: The user-visible name of the consumption preferences category. :param list[ConsumptionPreferences] consumption_preferences: Detailed results inferred from the input text for the individual preferences of the category. """ self.consumption_preference_category_id = consumption_preference_category_id self.name = name self.consumption_preferences = consumption_preferences @classmethod def _from_dict(cls, _dict): """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} if 'consumption_preference_category_id' in _dict: args['consumption_preference_category_id'] = _dict.get( 'consumption_preference_category_id') else: raise ValueError( 'Required property \'consumption_preference_category_id\' not present in ConsumptionPreferencesCategory JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in ConsumptionPreferencesCategory JSON' ) if 'consumption_preferences' in _dict: args['consumption_preferences'] = [ ConsumptionPreferences._from_dict(x) for x in (_dict.get('consumption_preferences')) ] else: raise ValueError( 'Required property \'consumption_preferences\' not present in ConsumptionPreferencesCategory JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'consumption_preference_category_id' ) and self.consumption_preference_category_id is not None: _dict[ 'consumption_preference_category_id'] = self.consumption_preference_category_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'consumption_preferences' ) and self.consumption_preferences is not None: _dict['consumption_preferences'] = [ x._to_dict() for x in self.consumption_preferences ] return _dict def __str__(self): """Return a `str` version of this ConsumptionPreferencesCategory object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Content(object): """ Content. :attr list[ContentItem] content_items: An array of `ContentItem` objects that provides the text that is to be analyzed. """ def __init__(self, content_items): """ Initialize a Content object. :param list[ContentItem] content_items: An array of `ContentItem` objects that provides the text that is to be analyzed. """ self.content_items = content_items @classmethod def _from_dict(cls, _dict): """Initialize a Content object from a json dictionary.""" args = {} if 'contentItems' in _dict: args['content_items'] = [ ContentItem._from_dict(x) for x in (_dict.get('contentItems')) ] else: raise ValueError( 'Required property \'contentItems\' not present in Content JSON' ) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'content_items') and self.content_items is not None: _dict['contentItems'] = [x._to_dict() for x in self.content_items] return _dict def __str__(self): """Return a `str` version of this Content object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ContentItem(object): """ ContentItem. :attr str content: The content that is to be analyzed. The service supports up to 20 MB of content for all `ContentItem` objects combined. :attr str id: (optional) A unique identifier for this content item. :attr int created: (optional) A timestamp that identifies when this content was created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. :attr int updated: (optional) A timestamp that identifies when this content was last updated. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. :attr str contenttype: (optional) The MIME type of the content. The default is plain text. The tags are stripped from HTML content before it is analyzed; plain text is processed as submitted. :attr str language: (optional) The language identifier (two-letter ISO 639-1 identifier) for the language of the content item. The default is `en` (English). Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. A language specified with the **Content-Type** parameter overrides the value of this parameter; any content items that specify a different language are ignored. Omit the **Content-Type** parameter to base the language on the most prevalent specification among the content items; again, content items that specify a different language are ignored. You can specify any combination of languages for the input and response content. :attr str parentid: (optional) The unique ID of the parent content item for this item. Used to identify hierarchical relationships between posts/replies, messages/replies, and so on. :attr bool reply: (optional) Indicates whether this content item is a reply to another content item. :attr bool forward: (optional) Indicates whether this content item is a forwarded/copied version of another content item. """ def __init__(self, content, id=None, created=None, updated=None, contenttype=None, language=None, parentid=None, reply=None, forward=None): """ Initialize a ContentItem object. :param str content: The content that is to be analyzed. The service supports up to 20 MB of content for all `ContentItem` objects combined. :param str id: (optional) A unique identifier for this content item. :param int created: (optional) A timestamp that identifies when this content was created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. :param int updated: (optional) A timestamp that identifies when this content was last updated. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. :param str contenttype: (optional) The MIME type of the content. The default is plain text. The tags are stripped from HTML content before it is analyzed; plain text is processed as submitted. :param str language: (optional) The language identifier (two-letter ISO 639-1 identifier) for the language of the content item. The default is `en` (English). Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. A language specified with the **Content-Type** parameter overrides the value of this parameter; any content items that specify a different language are ignored. Omit the **Content-Type** parameter to base the language on the most prevalent specification among the content items; again, content items that specify a different language are ignored. You can specify any combination of languages for the input and response content. :param str parentid: (optional) The unique ID of the parent content item for this item. Used to identify hierarchical relationships between posts/replies, messages/replies, and so on. :param bool reply: (optional) Indicates whether this content item is a reply to another content item. :param bool forward: (optional) Indicates whether this content item is a forwarded/copied version of another content item. """ self.content = content self.id = id self.created = created self.updated = updated self.contenttype = contenttype self.language = language self.parentid = parentid self.reply = reply self.forward = forward @classmethod def _from_dict(cls, _dict): """Initialize a ContentItem object from a json dictionary.""" args = {} if 'content' in _dict: args['content'] = _dict.get('content') else: raise ValueError( 'Required property \'content\' not present in ContentItem JSON') if 'id' in _dict: args['id'] = _dict.get('id') if 'created' in _dict: args['created'] = _dict.get('created') if 'updated' in _dict: args['updated'] = _dict.get('updated') if 'contenttype' in _dict: args['contenttype'] = _dict.get('contenttype') if 'language' in _dict: args['language'] = _dict.get('language') if 'parentid' in _dict: args['parentid'] = _dict.get('parentid') if 'reply' in _dict: args['reply'] = _dict.get('reply') if 'forward' in _dict: args['forward'] = _dict.get('forward') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'content') and self.content is not None: _dict['content'] = self.content if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasattr(self, 'created') and self.created is not None: _dict['created'] = self.created if hasattr(self, 'updated') and self.updated is not None: _dict['updated'] = self.updated if hasattr(self, 'contenttype') and self.contenttype is not None: _dict['contenttype'] = self.contenttype if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'parentid') and self.parentid is not None: _dict['parentid'] = self.parentid if hasattr(self, 'reply') and self.reply is not None: _dict['reply'] = self.reply if hasattr(self, 'forward') and self.forward is not None: _dict['forward'] = self.forward return _dict def __str__(self): """Return a `str` version of this ContentItem object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Profile(object): """ Profile. :attr str processed_language: The language model that was used to process the input. :attr int word_count: The number of words from the input that were used to produce the profile. :attr str word_count_message: (optional) When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. :attr list[Trait] personality: A recursive array of `Trait` objects that provides detailed results for the Big Five personality characteristics (dimensions and facets) inferred from the input text. :attr list[Trait] needs: Detailed results for the Needs characteristics inferred from the input text. :attr list[Trait] values: Detailed results for the Values characteristics inferred from the input text. :attr list[Behavior] behavior: (optional) For JSON content that is timestamped, detailed results about the social behavior disclosed by the input in terms of temporal characteristics. The results include information about the distribution of the content over the days of the week and the hours of the day. :attr list[ConsumptionPreferencesCategory] consumption_preferences: (optional) If the **consumption_preferences** parameter is `true`, detailed results for each category of consumption preferences. Each element of the array provides information inferred from the input text for the individual preferences of that category. :attr list[Warning] warnings: Warning messages associated with the input text submitted with the request. The array is empty if the input generated no warnings. """ def __init__(self, processed_language, word_count, personality, needs, values, warnings, word_count_message=None, behavior=None, consumption_preferences=None): """ Initialize a Profile object. :param str processed_language: The language model that was used to process the input. :param int word_count: The number of words from the input that were used to produce the profile. :param list[Trait] personality: A recursive array of `Trait` objects that provides detailed results for the Big Five personality characteristics (dimensions and facets) inferred from the input text. :param list[Trait] needs: Detailed results for the Needs characteristics inferred from the input text. :param list[Trait] values: Detailed results for the Values characteristics inferred from the input text. :param list[Warning] warnings: Warning messages associated with the input text submitted with the request. The array is empty if the input generated no warnings. :param str word_count_message: (optional) When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. :param list[Behavior] behavior: (optional) For JSON content that is timestamped, detailed results about the social behavior disclosed by the input in terms of temporal characteristics. The results include information about the distribution of the content over the days of the week and the hours of the day. :param list[ConsumptionPreferencesCategory] consumption_preferences: (optional) If the **consumption_preferences** parameter is `true`, detailed results for each category of consumption preferences. Each element of the array provides information inferred from the input text for the individual preferences of that category. """ self.processed_language = processed_language self.word_count = word_count self.word_count_message = word_count_message self.personality = personality self.needs = needs self.values = values self.behavior = behavior self.consumption_preferences = consumption_preferences self.warnings = warnings @classmethod def _from_dict(cls, _dict): """Initialize a Profile object from a json dictionary.""" args = {} if 'processed_language' in _dict: args['processed_language'] = _dict.get('processed_language') else: raise ValueError( 'Required property \'processed_language\' not present in Profile JSON' ) if 'word_count' in _dict: args['word_count'] = _dict.get('word_count') else: raise ValueError( 'Required property \'word_count\' not present in Profile JSON') if 'word_count_message' in _dict: args['word_count_message'] = _dict.get('word_count_message') if 'personality' in _dict: args['personality'] = [ Trait._from_dict(x) for x in (_dict.get('personality')) ] else: raise ValueError( 'Required property \'personality\' not present in Profile JSON') if 'needs' in _dict: args['needs'] = [Trait._from_dict(x) for x in (_dict.get('needs'))] else: raise ValueError( 'Required property \'needs\' not present in Profile JSON') if 'values' in _dict: args['values'] = [ Trait._from_dict(x) for x in (_dict.get('values')) ] else: raise ValueError( 'Required property \'values\' not present in Profile JSON') if 'behavior' in _dict: args['behavior'] = [ Behavior._from_dict(x) for x in (_dict.get('behavior')) ] if 'consumption_preferences' in _dict: args['consumption_preferences'] = [ ConsumptionPreferencesCategory._from_dict(x) for x in (_dict.get('consumption_preferences')) ] if 'warnings' in _dict: args['warnings'] = [ Warning._from_dict(x) for x in (_dict.get('warnings')) ] else: raise ValueError( 'Required property \'warnings\' not present in Profile JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr( self, 'processed_language') and self.processed_language is not None: _dict['processed_language'] = self.processed_language if hasattr(self, 'word_count') and self.word_count is not None: _dict['word_count'] = self.word_count if hasattr( self, 'word_count_message') and self.word_count_message is not None: _dict['word_count_message'] = self.word_count_message if hasattr(self, 'personality') and self.personality is not None: _dict['personality'] = [x._to_dict() for x in self.personality] if hasattr(self, 'needs') and self.needs is not None: _dict['needs'] = [x._to_dict() for x in self.needs] if hasattr(self, 'values') and self.values is not None: _dict['values'] = [x._to_dict() for x in self.values] if hasattr(self, 'behavior') and self.behavior is not None: _dict['behavior'] = [x._to_dict() for x in self.behavior] if hasattr(self, 'consumption_preferences' ) and self.consumption_preferences is not None: _dict['consumption_preferences'] = [ x._to_dict() for x in self.consumption_preferences ] if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict def __str__(self): """Return a `str` version of this Profile object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Trait(object): """ Trait. :attr str trait_id: The unique, non-localized identifier of the characteristic to which the results pertain. IDs have the form * `big5_{characteristic}` for Big Five personality dimensions * `facet_{characteristic}` for Big Five personality facets * `need_{characteristic}` for Needs *`value_{characteristic}` for Values. :attr str name: The user-visible, localized name of the characteristic. :attr str category: The category of the characteristic: `personality` for Big Five personality characteristics, `needs` for Needs, and `values` for Values. :attr float percentile: The normalized percentile score for the characteristic. The range is 0 to 1. For example, if the percentage for Openness is 0.60, the author scored in the 60th percentile; the author is more open than 59 percent of the population and less open than 39 percent of the population. :attr float raw_score: (optional) The raw score for the characteristic. The range is 0 to 1. A higher score generally indicates a greater likelihood that the author has that characteristic, but raw scores must be considered in aggregate: The range of values in practice might be much smaller than 0 to 1, so an individual score must be considered in the context of the overall scores and their range. The raw score is computed based on the input and the service model; it is not normalized or compared with a sample population. The raw score enables comparison of the results against a different sampling population and with a custom normalization approach. :attr bool significant: (optional) **`2017-10-13`**: Indicates whether the characteristic is meaningful for the input language. The field is always `true` for all characteristics of English, Spanish, and Japanese input. The field is `false` for the subset of characteristics of Arabic and Korean input for which the service's models are unable to generate meaningful results. **`2016-10-19`**: Not returned. :attr list[Trait] children: (optional) For `personality` (Big Five) dimensions, more detailed results for the facets of each dimension as inferred from the input text. """ def __init__(self, trait_id, name, category, percentile, raw_score=None, significant=None, children=None): """ Initialize a Trait object. :param str trait_id: The unique, non-localized identifier of the characteristic to which the results pertain. IDs have the form * `big5_{characteristic}` for Big Five personality dimensions * `facet_{characteristic}` for Big Five personality facets * `need_{characteristic}` for Needs *`value_{characteristic}` for Values. :param str name: The user-visible, localized name of the characteristic. :param str category: The category of the characteristic: `personality` for Big Five personality characteristics, `needs` for Needs, and `values` for Values. :param float percentile: The normalized percentile score for the characteristic. The range is 0 to 1. For example, if the percentage for Openness is 0.60, the author scored in the 60th percentile; the author is more open than 59 percent of the population and less open than 39 percent of the population. :param float raw_score: (optional) The raw score for the characteristic. The range is 0 to 1. A higher score generally indicates a greater likelihood that the author has that characteristic, but raw scores must be considered in aggregate: The range of values in practice might be much smaller than 0 to 1, so an individual score must be considered in the context of the overall scores and their range. The raw score is computed based on the input and the service model; it is not normalized or compared with a sample population. The raw score enables comparison of the results against a different sampling population and with a custom normalization approach. :param bool significant: (optional) **`2017-10-13`**: Indicates whether the characteristic is meaningful for the input language. The field is always `true` for all characteristics of English, Spanish, and Japanese input. The field is `false` for the subset of characteristics of Arabic and Korean input for which the service's models are unable to generate meaningful results. **`2016-10-19`**: Not returned. :param list[Trait] children: (optional) For `personality` (Big Five) dimensions, more detailed results for the facets of each dimension as inferred from the input text. """ self.trait_id = trait_id self.name = name self.category = category self.percentile = percentile self.raw_score = raw_score self.significant = significant self.children = children @classmethod def _from_dict(cls, _dict): """Initialize a Trait object from a json dictionary.""" args = {} if 'trait_id' in _dict: args['trait_id'] = _dict.get('trait_id') else: raise ValueError( 'Required property \'trait_id\' not present in Trait JSON') if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( 'Required property \'name\' not present in Trait JSON') if 'category' in _dict: args['category'] = _dict.get('category') else: raise ValueError( 'Required property \'category\' not present in Trait JSON') if 'percentile' in _dict: args['percentile'] = _dict.get('percentile') else: raise ValueError( 'Required property \'percentile\' not present in Trait JSON') if 'raw_score' in _dict: args['raw_score'] = _dict.get('raw_score') if 'significant' in _dict: args['significant'] = _dict.get('significant') if 'children' in _dict: args['children'] = [ Trait._from_dict(x) for x in (_dict.get('children')) ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'trait_id') and self.trait_id is not None: _dict['trait_id'] = self.trait_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'category') and self.category is not None: _dict['category'] = self.category if hasattr(self, 'percentile') and self.percentile is not None: _dict['percentile'] = self.percentile if hasattr(self, 'raw_score') and self.raw_score is not None: _dict['raw_score'] = self.raw_score if hasattr(self, 'significant') and self.significant is not None: _dict['significant'] = self.significant if hasattr(self, 'children') and self.children is not None: _dict['children'] = [x._to_dict() for x in self.children] return _dict def __str__(self): """Return a `str` version of this Trait object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other class Warning(object): """ Warning. :attr str warning_id: The identifier of the warning message. :attr str message: The message associated with the `warning_id`: * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a minimum of 600, preferably 1,200 or more, to compute statistically significant estimates." * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, however detected a JSON input. Did you mean application/json?" * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing processing time, only the first 250KB of input text (excluding markup) was analyzed. Accuracy levels off at approximately 3,000 words so this did not affect the accuracy of the profile." * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was trimmed for performance reasons. This action does not affect the accuracy of the output, as not all of the input text was required." Applies only when Arabic input text exceeds a threshold at which additional words do not contribute to the accuracy of the profile. """ def __init__(self, warning_id, message): """ Initialize a Warning object. :param str warning_id: The identifier of the warning message. :param str message: The message associated with the `warning_id`: * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a minimum of 600, preferably 1,200 or more, to compute statistically significant estimates." * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, however detected a JSON input. Did you mean application/json?" * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing processing time, only the first 250KB of input text (excluding markup) was analyzed. Accuracy levels off at approximately 3,000 words so this did not affect the accuracy of the profile." * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was trimmed for performance reasons. This action does not affect the accuracy of the output, as not all of the input text was required." Applies only when Arabic input text exceeds a threshold at which additional words do not contribute to the accuracy of the profile. """ self.warning_id = warning_id self.message = message @classmethod def _from_dict(cls, _dict): """Initialize a Warning object from a json dictionary.""" args = {} if 'warning_id' in _dict: args['warning_id'] = _dict.get('warning_id') else: raise ValueError( 'Required property \'warning_id\' not present in Warning JSON') if 'message' in _dict: args['message'] = _dict.get('message') else: raise ValueError( 'Required property \'message\' not present in Warning JSON') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'warning_id') and self.warning_id is not None: _dict['warning_id'] = self.warning_id if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message return _dict def __str__(self): """Return a `str` version of this Warning object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other watson-developer-cloud-2.10.1/watson_developer_cloud/speech_to_text_v1_adapter.py0000644000076500000240000003442413451407070032114 0ustar erikadsouzastaff00000000000000# coding: utf-8 # Copyright 2018 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from watson_developer_cloud.websocket import RecognizeCallback, RecognizeListener, AudioSource from .speech_to_text_v1 import SpeechToTextV1 from .watson_service import _remove_null_values import base64 try: from urllib.parse import urlencode except ImportError: from urllib import urlencode BEARER = 'Bearer' class SpeechToTextV1Adapter(SpeechToTextV1): def recognize_using_websocket(self, audio, content_type, recognize_callback, model=None, language_customization_id=None, acoustic_customization_id=None, customization_weight=None, base_model_version=None, inactivity_timeout=None, interim_results=None, keywords=None, keywords_threshold=None, max_alternatives=None, word_alternatives_threshold=None, word_confidence=None, timestamps=None, profanity_filter=None, smart_formatting=None, speaker_labels=None, http_proxy_host=None, http_proxy_port=None, customization_id=None, grammar_name=None, redaction=None, **kwargs): """ Sends audio for speech recognition using web sockets. :param AudioSource audio: The audio to transcribe in the format specified by the `Content-Type` header. :param str content_type: The type of the input: audio/basic, audio/flac, audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg, audio/ogg;codecs=opus, audio/ogg;codecs=vorbis, audio/wav, audio/webm, audio/webm;codecs=opus, or audio/webm;codecs=vorbis. :param RecognizeCallback recognize_callback: The callback method for the websocket. :param str model: The identifier of the model that is to be used for the recognition request or, for the **Create a session** method, with the new session. :param str language_customization_id: The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match the model specified with the `model` parameter. You must make the request with service credentials created for the instance of the service that owns the custom model. By default, no custom language model is used. See [Custom models](https://console.bluemix.net/docs/services/speech-to-text/input.html#custom). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: The customization ID (GUID) of a custom acoustic model that is to be used with the recognition request or, for the **Create a session** method, with the new session. The base model of the specified custom acoustic model must match the model specified with the `model` parameter. You must make the request with service credentials created for the instance of the service that owns the custom model. By default, no custom acoustic model is used. :param float customization_weight: If you specify the customization ID (GUID) of a custom language model with the recognition request or, for sessions, with the **Create a session** method, the customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model when it was trained, the default value is 0.3. A customization weight that you specify overrides a weight that was specified when the custom model was trained. The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. :param str base_model_version: The version of the specified base model that is to be used with recognition request or, for the **Create a session** method, with the new session. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The default value depends on whether the parameter is used with or without a custom model. For more information, see [Base model version](https://console.bluemix.net/docs/services/speech-to-text/input.html#version). :param int inactivity_timeout: The time in seconds after which, if only silence (no speech) is detected in submitted audio, the connection is closed with a 400 error. Useful for stopping audio submission from a live microphone when a user simply walks away. Use `-1` for infinity. :param list[str] keywords: An array of keyword strings to spot in the audio. Each keyword string can include one or more tokens. Keywords are spotted only in the final hypothesis, not in interim results. If you specify any keywords, you must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter or specify an empty array if you do not need to spot keywords. :param float keywords_threshold: A confidence value that is the lower bound for spotting a keyword. A word is considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability between 0 and 1 inclusive. No keyword spotting is performed if you omit the parameter. If you specify a threshold, you must also specify one or more keywords. :param int max_alternatives: The maximum number of alternative transcripts to be returned. By default, a single transcription is returned. :param float word_alternatives_threshold: A confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as \"Confusion Networks\"). An alternative word is considered if its confidence is greater than or equal to the threshold. Specify a probability between 0 and 1 inclusive. No alternative words are computed if you omit the parameter. :param bool word_confidence: If `true`, a confidence measure in the range of 0 to 1 is returned for each word. By default, no word confidence measures are returned. :param bool timestamps: If `true`, time alignment is returned for each word. By default, no timestamps are returned. :param bool profanity_filter: If `true` (the default), filters profanity from all output except for keyword results by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US English transcription only. :param bool smart_formatting: If `true`, converts dates, times, series of digits and numbers, phone numbers, currency values, and internet addresses into more readable, conventional representations in the final transcript of a recognition request. For US English, also converts certain keyword strings to punctuation symbols. By default, no smart formatting is performed. Applies to US English and Spanish transcription only. :param bool speaker_labels: If `true`, the response includes labels that identify which words were spoken by which participants in a multi-person exchange. By default, no speaker labels are returned. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. To determine whether a language model supports speaker labels, use the **Get models** method and check that the attribute `speaker_labels` is set to `true`. You can also refer to [Speaker labels](https://console.bluemix.net/docs/services/speech-to-text/output.html#speaker_labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param str customization_id: **Deprecated.** Use the `language_customization_id` parameter to specify the customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not specify both parameters with a request. :param str grammar_name: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified grammar; it does not recognize other custom words from the model's words resource. See [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/output.html). :param bool redaction: If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no redaction. When you enable redaction, the service automatically enables smart formatting, regardless of whether you explicitly disable that feature. To ensure maximum security, the service also disables keyword spotting (ignores the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the `max_alternatives` parameter to be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/services/speech-to-text/output.html#redaction). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict """ if audio is None: raise ValueError('audio must be provided') if not isinstance(audio, AudioSource): raise Exception( 'audio is not of type AudioSource. Import the class from watson_developer_cloud.websocket') if content_type is None: raise ValueError('content_type must be provided') if recognize_callback is None: raise ValueError('recognize_callback must be provided') if not isinstance(recognize_callback, RecognizeCallback): raise Exception( 'Callback is not a derived class of RecognizeCallback') headers = {} if self.default_headers is not None: headers = self.default_headers.copy() if 'headers' in kwargs: headers.update(kwargs.get('headers')) if self.token_manager: access_token = self.token_manager.get_token() headers['Authorization'] = '{0} {1}'.format(BEARER, access_token) else: authstring = "{0}:{1}".format(self.username, self.password) base64_authorization = base64.b64encode(authstring.encode('utf-8')).decode('utf-8') headers['Authorization'] = 'Basic {0}'.format(base64_authorization) url = self.url.replace('https:', 'wss:') params = { 'model': model, 'customization_id': customization_id, 'acoustic_customization_id': acoustic_customization_id, 'customization_weight': customization_weight, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id } params = _remove_null_values(params) url += '/v1/recognize?{0}'.format(urlencode(params)) options = { 'content_type': content_type, 'inactivity_timeout': inactivity_timeout, 'interim_results': interim_results, 'keywords': keywords, 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, 'word_alternatives_threshold': word_alternatives_threshold, 'word_confidence': word_confidence, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, 'speaker_labels': speaker_labels, 'grammar_name': grammar_name, 'redaction': redaction } options = _remove_null_values(options) RecognizeListener(audio, options, recognize_callback, url, headers, http_proxy_host, http_proxy_port, self.verify) watson-developer-cloud-2.10.1/examples/0000755000076500000240000000000013451440673021466 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/examples/tone_analyzer_v3.py0000755000076500000240000000576313451407070025332 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json from os.path import join, dirname from watson_developer_cloud import ToneAnalyzerV3 from watson_developer_cloud.tone_analyzer_v3 import ToneInput # If service instance provides API key authentication # service = ToneAnalyzerV3( # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/tone-analyzer/api', # version='2017-09-21', # iam_apikey='your_apikey') service = ToneAnalyzerV3( ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/tone-analyzer/api', username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', version='2017-09-21') print("\ntone_chat() example 1:\n") utterances = [{ 'text': 'I am very happy.', 'user': 'glenn' }, { 'text': 'It is a good day.', 'user': 'glenn' }] tone_chat = service.tone_chat(utterances).get_result() print(json.dumps(tone_chat, indent=2)) print("\ntone() example 1:\n") print( json.dumps( service.tone( tone_input='I am very happy. It is a good day.', content_type="text/plain").get_result(), indent=2)) print("\ntone() example 2:\n") with open(join(dirname(__file__), '../resources/tone-example.json')) as tone_json: tone = service.tone(json.load(tone_json)['text'], "text/plain").get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 3:\n") with open(join(dirname(__file__), '../resources/tone-example.json')) as tone_json: tone = service.tone( tone_input=json.load(tone_json)['text'], content_type='text/plain', sentences=True).get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 4:\n") with open(join(dirname(__file__), '../resources/tone-example.json')) as tone_json: tone = service.tone( tone_input=json.load(tone_json), content_type='application/json').get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 5:\n") with open(join(dirname(__file__), '../resources/tone-example-html.json')) as tone_html: tone = service.tone( json.load(tone_html)['text'], content_type='text/html').get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 6 with GDPR support:\n") service.set_detailed_response(True) with open(join(dirname(__file__), '../resources/tone-example-html.json')) as tone_html: tone = service.tone( json.load(tone_html)['text'], content_type='text/html', headers={ 'Custom-Header': 'custom_value' }) print(tone) print(tone.get_headers()) print(tone.get_result()) print(tone.get_status_code()) service.set_detailed_response(False) print("\ntone() example 7:\n") tone_input = ToneInput('I am very happy. It is a good day.') tone = service.tone(tone_input=tone_input, content_type="application/json") print(json.dumps(tone, indent=2)) watson-developer-cloud-2.10.1/examples/assistant_v2.py0000644000076500000240000000236413451407070024457 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json from watson_developer_cloud import AssistantV2 # If service instance provides API key authentication # assistant = AssistantV2( # version='2018-09-20', # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/assistant/api', # iam_apikey='iam_apikey') assistant = AssistantV2( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/assistant/api', version='2018-09-20') ######################### # Sessions ######################### session = assistant.create_session("").get_result() print(json.dumps(session, indent=2)) assistant.delete_session("", "").get_result() ######################### # Message ######################### message = assistant.message( "", "", input={'text': 'What\'s the weather like?'}, context={ 'metadata': { 'deployment': 'myDeployment' } }).get_result() print(json.dumps(message, indent=2)) watson-developer-cloud-2.10.1/examples/authorization_v1.py0000644000076500000240000000047713451407070025350 0ustar erikadsouzastaff00000000000000import json from watson_developer_cloud import AuthorizationV1 from watson_developer_cloud import SpeechToTextV1 authorization = AuthorizationV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') print( json.dumps( authorization.get_token(url=SpeechToTextV1.default_url), indent=2)) watson-developer-cloud-2.10.1/examples/speaker_text_to_speech.py0000644000076500000240000000714413451407070026567 0ustar erikadsouzastaff00000000000000# You need to install pyaudio to run this example # pip install pyaudio # In this example, the websocket connection is opened with a text # passed in the request. When the service responds with the synthesized # audio, the pyaudio would play it in a blocking mode from __future__ import print_function from watson_developer_cloud import TextToSpeechV1 from watson_developer_cloud.websocket import SynthesizeCallback import pyaudio # If service instance provides API key authentication service = TextToSpeechV1( ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://stream.watsonplatform.net/text-to-speech/api', iam_apikey='your_apikey') # service = TextToSpeechV1( # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # # url='https://stream.watsonplatform.net/text-to-speech/api, # username='YOUR SERVICE USERNAME', # password='YOUR SERVICE PASSWORD') class Play(object): """ Wrapper to play the audio in a blocking mode """ def __init__(self): self.format = pyaudio.paInt16 self.channels = 1 self.rate = 22050 self.chunk = 1024 self.pyaudio = None self.stream = None def start_streaming(self): self.pyaudio = pyaudio.PyAudio() self.stream = self._open_stream() self._start_stream() def _open_stream(self): stream = self.pyaudio.open( format=self.format, channels=self.channels, rate=self.rate, output=True, frames_per_buffer=self.chunk, start=False ) return stream def _start_stream(self): self.stream.start_stream() def write_stream(self, audio_stream): self.stream.write(audio_stream) def complete_playing(self): self.stream.stop_stream() self.stream.close() self.pyaudio.terminate() class MySynthesizeCallback(SynthesizeCallback): def __init__(self): SynthesizeCallback.__init__(self) self.play = Play() def on_connected(self): print('Opening stream to play') self.play.start_streaming() def on_error(self, error): print('Error received: {}'.format(error)) def on_timing_information(self, timing_information): print(timing_information) def on_audio_stream(self, audio_stream): self.play.write_stream(audio_stream) def on_close(self): print('Completed synthesizing') self.play.complete_playing() test_callback = MySynthesizeCallback() # An example SSML text SSML_sorry_text = """ I am sorry, I know how it feels. """ # Another example of SSML text SSML_text = """ I have been assigned to handle your order status request. I am sorry to inform you that the items you requested are backordered. We apologize for the inconvenience. We don't know when the items will become available. Maybe next week, but we are not sure at this time. But because we want you to be a satisfied customer, we are giving you a 50% discount on your order! """ service.synthesize_using_websocket(SSML_text, test_callback, accept='audio/wav', voice="en-US_AllisonVoice" ) watson-developer-cloud-2.10.1/examples/visual_recognition_v3.py0000644000076500000240000000463313451407070026353 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json from os.path import abspath from watson_developer_cloud import VisualRecognitionV3, WatsonApiException test_url = 'https://www.ibm.com/ibm/ginni/images' \ '/ginni_bio_780x981_v4_03162016.jpg' # If service instance provides IAM API key authentication service = VisualRecognitionV3( '2018-03-19', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/visual-recognition/api', iam_apikey='iam_apikey') # with open(abspath('resources/cars.zip'), 'rb') as cars, \ # open(abspath('resources/trucks.zip'), 'rb') as trucks: # classifier = service.create_classifier('Cars vs Trucks', # cars_positive_examples=cars, # negative_examples=trucks).get_result() # print(json.dumps(classifier, indent=2)) car_path = abspath("resources/cars.zip") try: with open(car_path, 'rb') as images_file: car_results = service.classify( images_file=images_file, threshold='0.1', classifier_ids=['default']).get_result() print(json.dumps(car_results, indent=2)) except WatsonApiException as ex: print(ex) # classifier = service.get_classifier('YOUR CLASSIFIER ID').get_result() # print(json.dumps(classifier, indent=2)) # with open(abspath('resources/car.jpg'), 'rb') as image_file: # classifier = service.update_classifier('CarsvsTrucks_1479118188', # cars_positive_examples=image_file).get_result() # print(json.dumps(classifier, indent=2)) # faces_result = service.detect_faces(url=test_url).get_result() # print(json.dumps(faces_result, indent=2)) # response = service.delete_classifier(classifier_id='YOUR CLASSIFIER ID').get_result() # print(json.dumps(response, indent=2)) classifiers = service.list_classifiers().get_result() print(json.dumps(classifiers, indent=2)) face_path = abspath('resources/face.jpg') with open(face_path, 'rb') as image_file: face_result = service.detect_faces(images_file=image_file).get_result() print(json.dumps(face_result, indent=2)) #Core ml model example # model_name = '{0}.mlmodel'.format(classifier_id) # core_ml_model = service.get_core_ml_model(classifier_id).get_result() # with open('/tmp/{0}'.format(model_name), 'wb') as fp: # fp.write(core_ml_model.content) watson-developer-cloud-2.10.1/examples/speech_to_text_v1.py0000644000076500000240000000417313451407070025462 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json from os.path import join, dirname from watson_developer_cloud import SpeechToTextV1 from watson_developer_cloud.websocket import RecognizeCallback, AudioSource import threading # If service instance provides API key authentication # service = SpeechToTextV1( # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://stream.watsonplatform.net/speech-to-text/api', # iam_apikey='your_apikey') service = SpeechToTextV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', url='https://stream.watsonplatform.net/speech-to-text/api') models = service.list_models().get_result() print(json.dumps(models, indent=2)) model = service.get_model('en-US_BroadbandModel').get_result() print(json.dumps(model, indent=2)) with open(join(dirname(__file__), '../resources/speech.wav'), 'rb') as audio_file: print(json.dumps( service.recognize( audio=audio_file, content_type='audio/wav', timestamps=True, word_confidence=True).get_result(), indent=2)) # Example using websockets class MyRecognizeCallback(RecognizeCallback): def __init__(self): RecognizeCallback.__init__(self) def on_transcription(self, transcript): print(transcript) def on_connected(self): print('Connection was successful') def on_error(self, error): print('Error received: {}'.format(error)) def on_inactivity_timeout(self, error): print('Inactivity timeout: {}'.format(error)) def on_listening(self): print('Service is listening') def on_hypothesis(self, hypothesis): print(hypothesis) def on_data(self, data): print(data) # Example using threads in a non-blocking way mycallback = MyRecognizeCallback() audio_file = open(join(dirname(__file__), '../resources/speech.wav'), 'rb') audio_source = AudioSource(audio_file) recognize_thread = threading.Thread( target=service.recognize_using_websocket, args=(audio_source, "audio/l16; rate=44100", mycallback)) recognize_thread.start() watson-developer-cloud-2.10.1/examples/__init__.py0000644000076500000240000000111513172173716023576 0ustar erikadsouzastaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. watson-developer-cloud-2.10.1/examples/language_translator_v3.py0000644000076500000240000000346113451407070026502 0ustar erikadsouzastaff00000000000000# coding=utf-8 from __future__ import print_function import json from watson_developer_cloud import LanguageTranslatorV3 # language_translator = LanguageTranslatorV3( # version='2018-05-01.', # ### url is optional, and defaults to the URL below. Use the correct URL for your region. # # url='https://gateway.watsonplatform.net/language-translator/api', # iam_apikey='your_apikey') # Authenticate with username/password if your service instance doesn't provide an API key language_translator = LanguageTranslatorV3( version='2018-05-01.', username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') ## Translate translation = language_translator.translate( text='Hello', model_id='en-es').get_result() print(json.dumps(translation, indent=2, ensure_ascii=False)) # List identifiable languages # languages = language_translator.list_identifiable_languages().get_result() # print(json.dumps(languages, indent=2)) # # Identify # language = language_translator.identify( # 'Language translator translates text from one language to another').get_result() # print(json.dumps(language, indent=2)) # # List models # models = language_translator.list_models( # source='en').get_result() # print(json.dumps(models, indent=2)) # # Create model # with open('glossary.tmx', 'rb') as glossary: # response = language_translator.create_model( # base_model_id='en-es', # name='custom-english-to-spanish', # forced_glossary=glossary).get_result() # print(json.dumps(response, indent=2)) # # Delete model # response = language_translator.delete_model(model_id='').get_result() # print(json.dumps(response, indent=2)) # # Get model details # model = language_translator.get_model(model_id='').get_result() # print(json.dumps(model, indent=2)) watson-developer-cloud-2.10.1/examples/README.md0000644000076500000240000000071413346311705022743 0ustar erikadsouzastaff00000000000000## Examples To run the examples, you will need the appropriate service instance 1. Go to the IBM Cloud [Dashboard](https://console.bluemix.net/dashboard/apps?category=ai) page. 1. Either click an existing Watson service instance or click [**Create resource > AI**](https://console.bluemix.net/catalog/?category=ai) and create a service instance. 1. Copy the `url` and either `apikey` or `username` and `password`. Click **Show** if the credentials are masked.watson-developer-cloud-2.10.1/examples/discovery_v1.py0000644000076500000240000000641013451407070024450 0ustar erikadsouzastaff00000000000000# coding: utf-8 from __future__ import print_function import json from watson_developer_cloud import DiscoveryV1 # If service instance provides API key authentication # discovery = DiscoveryV1( # version='2018-08-01', # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/discovery/api', # iam_apikey='iam_apikey') discovery = DiscoveryV1( version='2018-08-01', ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/discovery/api', username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') environments = discovery.list_environments().get_result() print(json.dumps(environments, indent=2)) news_environment_id = 'system' print(json.dumps(news_environment_id, indent=2)) collections = discovery.list_collections(news_environment_id).get_result() news_collections = [x for x in collections['collections']] print(json.dumps(collections, indent=2)) configurations = discovery.list_configurations( environment_id=news_environment_id).get_result() print(json.dumps(configurations, indent=2)) query_results = discovery.query( news_environment_id, news_collections[0]['collection_id'], filter='extracted_metadata.sha1::f5*', return_fields='extracted_metadata.sha1').get_result() print(json.dumps(query_results, indent=2)) # new_environment = discovery.create_environment(name="new env", description="bogus env").get_result() # print(new_environment) # environment = discovery.get_environment(environment_id=new_environment['environment_id']).get_result() # if environment['status'] == 'active': # writable_environment_id = new_environment['environment_id'] # new_collection = discovery.create_collection(environment_id=writable_environment_id, # name='Example Collection', # description="just a test").get_result() # print(new_collection) # collections = discovery.list_collections(environment_id=writable_environment_id).get_result() # print(collections) # res = discovery.delete_collection(environment_id='', # collection_id=new_collection['collection_id']).get_result() # print(res) # collections = discovery.list_collections(environment_id=writable_environment_id).get_result() # print(collections) # # with open(os.path.join(os.getcwd(),'..', 'resources','simple.html')) as fileinfo: # # print(discovery.test_document(environment_id=writable_environment_id, fileinfo=fileinfo).get_result()) # with open(os.path.join(os.getcwd(), '..','resources', 'simple.html')) as fileinfo: # res = discovery.add_document(environment_id=writable_environment_id, # collection_id=collections['collections'][0]['collection_id'], # file=fileinfo).get_result() # print(res) # res = discovery.get_collection(environment_id=writable_environment_id, # collection_id=collections['collections'][0]['collection_id']).get_result() # print(res['document_counts']) #res = discovery.delete_environment(environment_id=writable_environment_id).get_result() #print(res) watson-developer-cloud-2.10.1/examples/microphone-speech-to-text.py0000644000076500000240000000742413451407070027053 0ustar erikadsouzastaff00000000000000# You need to install pyaudio to run this example # pip install pyaudio # When using a microphone, the AudioSource `input` parameter would be # initialised as a queue. The pyaudio stream would be continuosly adding # recordings to the queue, and the websocket client would be sending the # recordings to the speech to text service from __future__ import print_function import pyaudio from watson_developer_cloud import SpeechToTextV1 from watson_developer_cloud.websocket import RecognizeCallback, AudioSource from threading import Thread try: from Queue import Queue, Full except ImportError: from queue import Queue, Full ############################################### #### Initalize queue to store the recordings ## ############################################### CHUNK = 1024 # Note: It will discard if the websocket client can't consumme fast enough # So, increase the max size as per your choice BUF_MAX_SIZE = CHUNK * 10 # Buffer to store audio q = Queue(maxsize=int(round(BUF_MAX_SIZE / CHUNK))) # Create an instance of AudioSource audio_source = AudioSource(q, True, True) ############################################### #### Prepare Speech to Text Service ######## ############################################### # initialize speech to text service speech_to_text = SpeechToTextV1( iam_apikey='{YOUR_IAM_API_KEY}', url='{YOUR_GATEWAY_URL}') # define callback for the speech to text service class MyRecognizeCallback(RecognizeCallback): def __init__(self): RecognizeCallback.__init__(self) def on_transcription(self, transcript): print(transcript) def on_connected(self): print('Connection was successful') def on_error(self, error): print('Error received: {}'.format(error)) def on_inactivity_timeout(self, error): print('Inactivity timeout: {}'.format(error)) def on_listening(self): print('Service is listening') def on_hypothesis(self, hypothesis): print(hypothesis) def on_data(self, data): print(data) def on_close(self): print("Connection closed") # this function will initiate the recognize service and pass in the AudioSource def recognize_using_weboscket(*args): mycallback = MyRecognizeCallback() speech_to_text.recognize_using_websocket(audio=audio_source, content_type='audio/l16; rate=44100', recognize_callback=mycallback, interim_results=True) ############################################### #### Prepare the for recording using Pyaudio ## ############################################### # Variables for recording the speech FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 # define callback for pyaudio to store the recording in queue def pyaudio_callback(in_data, frame_count, time_info, status): try: q.put(in_data) except Full: pass # discard return (None, pyaudio.paContinue) # instantiate pyaudio audio = pyaudio.PyAudio() # open stream using callback stream = audio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, stream_callback=pyaudio_callback, start=False ) ######################################################################### #### Start the recording and start service to recognize the stream ###### ######################################################################### print("Enter CTRL+C to end recording...") stream.start_stream() try: recognize_thread = Thread(target=recognize_using_weboscket, args=()) recognize_thread.start() while True: pass except KeyboardInterrupt: # stop recording audio_source.completed_recording() stream.stop_stream() stream.close() audio.terminate() watson-developer-cloud-2.10.1/examples/natural_language_classifier_v1.py0000644000076500000240000000414313451407070030157 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json import os # from os.path import join, dirname from watson_developer_cloud import NaturalLanguageClassifierV1 # # If service instance provides API key authentication # service = NaturalLanguageClassifierV1( # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/natural-language-classifier/api', # iam_apikey='your_apikey') service = NaturalLanguageClassifierV1( ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/natural-language-classifier/api', username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') classifiers = service.list_classifiers().get_result() print(json.dumps(classifiers, indent=2)) # create a classifier with open( os.path.join( os.path.dirname(__file__), '../resources/weather_data_train.csv'), 'rb') as training_data: metadata = json.dumps({'name': 'my-classifier', 'language': 'en'}) classifier = service.create_classifier( metadata=metadata, training_data=training_data).get_result() classifier_id = classifier['classifier_id'] print(json.dumps(classifier, indent=2)) status = service.get_classifier(classifier_id).get_result() print(json.dumps(status, indent=2)) if status['status'] == 'Available': classes = service.classify(classifier_id, 'How hot will it be ' 'tomorrow?').get_result() print(json.dumps(classes, indent=2)) if status['status'] == 'Available': collection = [ '{"text":"How hot will it be today?"}', '{"text":"Is it hot outside?"}' ] classes = service.classify_collection(classifier_id, collection).get_result() print(json.dumps(classes, indent=2)) delete = service.delete_classifier(classifier_id).get_result() print(json.dumps(delete, indent=2)) # example of raising a ValueError # print(json.dumps( # service.create_classifier(training_data='', name='weather3', metadata='metadata'), # indent=2)) watson-developer-cloud-2.10.1/examples/conversation_tone_analyzer_integration/0000755000076500000240000000000013451440673031535 5ustar erikadsouzastaff00000000000000watson-developer-cloud-2.10.1/examples/conversation_tone_analyzer_integration/__init__.py0000644000076500000240000000144013451407070033637 0ustar erikadsouzastaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .watson_service import WatsonService from .watson_service import WatsonException from .conversation_v1 import ConversationV1 from .tone_analyzer_v3 import ToneAnalyzerV3 from .version import __version__ watson-developer-cloud-2.10.1/examples/conversation_tone_analyzer_integration/README.md0000644000076500000240000000430613451407070033011 0ustar erikadsouzastaff00000000000000# Conversation and Tone Analyzer Integration Example This example provides sample code for integrating [Tone Analyzer][tone_analyzer] and [Conversation][conversation] in Python 2.6+. All calls are made synchronously. For sample Python 3.5 asynchronous code, please see [https://github.com/aprilwebster/python-sdk][aprilwebster_python_sdk_github]. * [tone_detection.py][tone_conversation_integration_example_tone_detection] - sample code to initialize a user object in the conversation payload's context (initUser), to call Tone Analyzer to retrieve tone for a user's input (invokeToneAsync), and to update tone in the user object in the conversation payload's context (updateUserTone). * [tone_conversation_integration.v1.py][tone_conversation_integration_example] - sample code to use tone_detection.py to get and add tone to the payload and send a request to the Conversation Service's message endpoint both in a synchronous and asynchronous manner. Requirements to run the sample code * [Tone Analyzer Service credentials][ibm_cloud_tone_analyzer_service] * [Conversation Service credentials][ibm_cloud_conversation_service] * [Conversation Workspace ID][conversation_simple_workspace] Credentials & the Workspace ID can be set in environment properties, a .env file, or directly in the code. Dependencies provided in `init.py` Command to run the sample code `python tone_conversation_integration.v1.py` [conversation]: https://cloud.ibm.com/apidocs/assistant [tone_analyzer]: https://cloud.ibm.com/apidocs/tone-analyzer [ibm_cloud_conversation_service]: https://cloud.ibm.com/catalog/services/watson-assistant-formerly-conversation [ibm_cloud_tone_analyzer_service]: https://cloud.ibm.com/catalog/services/tone-analyzer [conversation_simple_workspace]: https://github.com/watson-developer-cloud/conversation-simple#workspace [tone_conversation_integration_example]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples/tone_conversation_integration.v1.py [tone_conversation_integration_example_tone_detection]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples/conversation_addons/tone_detection.py [aprilwebster_python_sdk_github]: https://github.com/aprilwebster/python-sdk././@LongLink0000000000000000000000000000016200000000000011214 Lustar 00000000000000watson-developer-cloud-2.10.1/examples/conversation_tone_analyzer_integration/tone_conversation_integration.v1.pywatson-developer-cloud-2.10.1/examples/conversation_tone_analyzer_integration/tone_conversation_inte0000644000076500000240000000547513451407070036243 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json import os from dotenv import load_dotenv, find_dotenv from watson_developer_cloud import ConversationV1 from watson_developer_cloud import ToneAnalyzerV3 # import tone detection import tone_detection # load the .env file containing your environment variables for the required # services (conversation and tone) load_dotenv(find_dotenv()) # replace with your own conversation credentials or put them in a .env file conversation = ConversationV1( username=os.environ.get('CONVERSATION_USERNAME') or 'YOUR SERVICE NAME', password=os.environ.get('CONVERSATION_PASSWORD') or 'YOUR PASSWORD', version='2016-09-20') # replace with your own tone analyzer credentials tone_analyzer = ToneAnalyzerV3( username=os.environ.get('TONE_ANALYZER_USERNAME') or 'YOUR SERVICE NAME', password=os.environ.get('TONE_ANALYZER_PASSWORD') or 'YOUR SERVICE NAME', version='2016-02-11') # replace with your own workspace_id workspace_id = os.environ.get('WORKSPACE_ID') or 'YOUR WORKSPACE ID' # This example stores tone for each user utterance in conversation context. # Change this to false, if you do not want to maintain history global_maintainToneHistoryInContext = True # Payload for the Watson Conversation Service # user input text required - replace "I am happy" with user input text. global_payload = { 'workspace_id': workspace_id, 'input': { 'text': "I am happy" } } def invokeToneConversation(payload, maintainToneHistoryInContext): """ invokeToneConversation calls the Tone Analyzer service to get the tone information for the user's input text (input['text'] in the payload json object), adds/updates the user's tone in the payload's context, and sends the payload to the conversation service to get a response which is printed to screen. :param payload: a json object containing the basic information needed to converse with the Conversation Service's message endpoint. :param maintainHistoryInContext: Note: as indicated below, the console.log statements can be replaced with application-specific code to process the err or data object returned by the Conversation Service. """ tone = tone_analyzer.tone(tone_input=payload['input']['text'], content_type='application/json').get_result() conversation_payload = tone_detection.\ updateUserTone(payload, tone, maintainToneHistoryInContext) response = conversation.message(workspace_id=workspace_id, input=conversation_payload['input'], context=conversation_payload['context']).get_result() print(json.dumps(response, indent=2)) # synchronous call to conversation with tone included in the context invokeToneConversation(global_payload, global_maintainToneHistoryInContext) watson-developer-cloud-2.10.1/examples/conversation_tone_analyzer_integration/tone_detection.py0000644000076500000240000002074113451407070035110 0ustar erikadsouzastaff00000000000000# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ * Thresholds for identifying meaningful tones returned by the Watson Tone Analyzer. Current values are * based on the recommendations made by the Watson Tone Analyzer at * https://console.bluemix.net/docs/services/tone-analyzer/using-tone.html * These thresholds can be adjusted to client/domain requirements. """ PRIMARY_EMOTION_SCORE_THRESHOLD = 0.5 WRITING_HIGH_SCORE_THRESHOLD = 0.75 WRITING_NO_SCORE_THRESHOLD = 0.0 SOCIAL_HIGH_SCORE_THRESHOLD = 0.75 SOCIAL_LOW_SCORE_THRESHOLD = 0.25 # Labels for the tone categories returned by the Watson Tone Analyzer EMOTION_TONE_LABEL = 'emotion_tone' WRITING_TONE_LABEL = 'writing_tone' SOCIAL_TONE_LABEL = 'social_tone' def updateUserTone(conversationPayload, toneAnalyzerPayload, maintainHistory): """ updateUserTone processes the Tone Analyzer payload to pull out the emotion, writing and social tones, and identify the meaningful tones (i.e., those tones that meet the specified thresholds). The conversationPayload json object is updated to include these tones. @param conversationPayload json object returned by the Watson Conversation Service @param toneAnalyzerPayload json object returned by the Watson Tone Analyzer Service @returns conversationPayload where the user object has been updated with tone information from the toneAnalyzerPayload """ emotionTone = None writingTone = None socialTone = None # if there is no context in a if 'context' not in conversationPayload: conversationPayload['context'] = {} if 'user' not in conversationPayload['context']: conversationPayload['context'] = initUser() # For convenience sake, define a variable for the user object user = conversationPayload['context']['user'] # Extract the tones - emotion, writing and social if toneAnalyzerPayload and toneAnalyzerPayload['document_tone']: for toneCategory in toneAnalyzerPayload['document_tone'][ 'tone_categories']: if toneCategory['category_id'] == EMOTION_TONE_LABEL: emotionTone = toneCategory if toneCategory['category_id'] == WRITING_TONE_LABEL: writingTone = toneCategory if toneCategory['category_id'] == SOCIAL_TONE_LABEL: socialTone = toneCategory updateEmotionTone(user, emotionTone, maintainHistory) updateWritingTone(user, writingTone, maintainHistory) updateSocialTone(user, socialTone, maintainHistory) conversationPayload['context']['user'] = user return conversationPayload def initUser(): """ initUser initializes a user object containing tone data (from the Watson Tone Analyzer) @returns user json object with the emotion, writing and social tones. The current tone identifies the tone for a specific conversation turn, and the history provides the conversation for all tones up to the current tone for a conversation instance with a user. """ return { 'user': { 'tone': { 'emotion': { 'current': None }, 'writing': { 'current': None }, 'social': { 'current': None } } } } def updateEmotionTone(user, emotionTone, maintainHistory): """ updateEmotionTone updates the user emotion tone with the primary emotion - the emotion tone that has a score greater than or equal to the EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral' @param user a json object representing user information (tone) to be used in conversing with the Conversation Service @param emotionTone a json object containing the emotion tones in the payload returned by the Tone Analyzer """ maxScore = 0.0 primaryEmotion = None primaryEmotionScore = None for tone in emotionTone['tones']: if tone['score'] > maxScore: maxScore = tone['score'] primaryEmotion = tone['tone_name'].lower() primaryEmotionScore = tone['score'] if maxScore <= PRIMARY_EMOTION_SCORE_THRESHOLD: primaryEmotion = 'neutral' primaryEmotionScore = None # update user emotion tone user['tone']['emotion']['current'] = primaryEmotion if maintainHistory: if 'history' not in user['tone']['emotion']: user['tone']['emotion']['history'] = [] user['tone']['emotion']['history'].append({ 'tone_name': primaryEmotion, 'score': primaryEmotionScore }) def updateWritingTone(user, writingTone, maintainHistory): """ updateWritingTone updates the user with the writing tones interpreted based on the specified thresholds @param: user a json object representing user information (tone) to be used in conversing with the Conversation Service @param: writingTone a json object containing the writing tones in the payload returned by the Tone Analyzer """ currentWriting = [] currentWritingObject = [] # Process each writing tone and determine if it is high or low for tone in writingTone['tones']: if tone['score'] >= WRITING_HIGH_SCORE_THRESHOLD: currentWriting.append(tone['tone_name'].lower() + '_high') currentWritingObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely high' }) elif tone['score'] <= WRITING_NO_SCORE_THRESHOLD: currentWritingObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'no evidence' }) else: currentWritingObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely medium' }) # update user writing tone user['tone']['writing']['current'] = currentWriting if maintainHistory: if 'history' not in user['tone']['writing']: user['tone']['writing']['history'] = [] user['tone']['writing']['history'].append(currentWritingObject) def updateSocialTone(user, socialTone, maintainHistory): """ updateSocialTone updates the user with the social tones interpreted based on the specified thresholds @param user a json object representing user information (tone) to be used in conversing with the Conversation Service @param socialTone a json object containing the social tones in the payload returned by the Tone Analyzer """ currentSocial = [] currentSocialObject = [] # Process each social tone and determine if it is high or low for tone in socialTone['tones']: if tone['score'] >= SOCIAL_HIGH_SCORE_THRESHOLD: currentSocial.append(tone['tone_name'].lower() + '_high') currentSocialObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely high' }) elif tone['score'] <= SOCIAL_LOW_SCORE_THRESHOLD: currentSocial.append(tone['tone_name'].lower() + '_low') currentSocialObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely low' }) else: currentSocialObject.append({ 'tone_name': tone['tone_name'].lower(), 'score': tone['score'], 'interpretation': 'likely medium' }) # update user social tone user['tone']['social']['current'] = currentSocial if maintainHistory: if not user['tone']['social']['current']: user['tone']['social']['current'] = [] user['tone']['social']['current'].append(currentSocialObject) watson-developer-cloud-2.10.1/examples/natural_language_understanding_v1.py0000644000076500000240000000222713451407070030701 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json from watson_developer_cloud import NaturalLanguageUnderstandingV1 from watson_developer_cloud.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions # If service instance provides API key authentication # service = NaturalLanguageUnderstandingV1( # version='2018-03-16', # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/natural-language-understanding/api', # iam_apikey='your_apikey') service = NaturalLanguageUnderstandingV1( version='2018-03-16', ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/natural-language-understanding/api', username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') response = service.analyze( text='Bruce Banner is the Hulk and Bruce Wayne is BATMAN! ' 'Superman fears not Banner, but Wayne.', features=Features(entities=EntitiesOptions(), keywords=KeywordsOptions())).get_result() print(json.dumps(response, indent=2)) watson-developer-cloud-2.10.1/examples/text_to_speech_v1.py0000644000076500000240000000667513451407070025473 0ustar erikadsouzastaff00000000000000# coding=utf-8 from __future__ import print_function import json from os.path import join, dirname from watson_developer_cloud import TextToSpeechV1 from watson_developer_cloud.websocket import SynthesizeCallback # If service instance provides API key authentication # service = TextToSpeechV1( # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://stream.watsonplatform.net/text-to-speech/api', # iam_apikey='your_apikey') service = TextToSpeechV1( ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://stream.watsonplatform.net/text-to-speech/api, username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') voices = service.list_voices().get_result() print(json.dumps(voices, indent=2)) with open(join(dirname(__file__), '../resources/output.wav'), 'wb') as audio_file: response = service.synthesize( 'Hello world!', accept='audio/wav', voice="en-US_AllisonVoice").get_result() audio_file.write(response.content) pronunciation = service.get_pronunciation('Watson', format='spr').get_result() print(json.dumps(pronunciation, indent=2)) voice_models = service.list_voice_models().get_result() print(json.dumps(voice_models, indent=2)) # voice_model = service.create_voice_model('test-customization').get_result() # print(json.dumps(voice_model, indent=2)) # updated_voice_model = service.update_voice_model( # 'YOUR CUSTOMIZATION ID', name='new name').get_result() # print(updated_voice_model) # voice_model = service.get_voice_model('YOUR CUSTOMIZATION ID').get_result() # print(json.dumps(voice_model, indent=2)) # words = service.list_words('YOUR CUSTOMIZATIONID').get_result() # print(json.dumps(words, indent=2)) # words = service.add_words('YOUR CUSTOMIZATION ID', [{ # 'word': 'resume', # 'translation': 'rɛzʊmeɪ' # }]).get_result() # print(words) # word = service.add_word( # 'YOUR CUSTOMIZATION ID', word='resume', translation='rɛzʊmeɪ').get_result() # print(word) # word = service.get_word('YOUR CUSTOMIZATIONID', 'resume').get_result() # print(json.dumps(word, indent=2)) # response = service.delete_word('YOUR CUSTOMIZATION ID', 'resume').get_result() # print(response) # response = service.delete_voice_model('YOUR CUSTOMIZATION ID').get_result() # print(response) # Synthesize using websocket. Note: The service accepts one request per connection file_path = join(dirname(__file__), "../resources/dog.wav") class MySynthesizeCallback(SynthesizeCallback): def __init__(self): SynthesizeCallback.__init__(self) self.fd = open(file_path, 'ab') def on_connected(self): print('Connection was successful') def on_error(self, error): print('Error received: {}'.format(error)) def on_content_type(self, content_type): print('Content type: {}'.format(content_type)) def on_timing_information(self, timing_information): print(timing_information) def on_audio_stream(self, audio_stream): self.fd.write(audio_stream) def on_close(self): self.fd.close() print('Done synthesizing. Closing the connection') my_callback = MySynthesizeCallback() service.synthesize_using_websocket('I like to pet dogs', my_callback, accept='audio/wav', voice='en-US_AllisonVoice' ) watson-developer-cloud-2.10.1/examples/assistant_v1.py0000644000076500000240000002516613451407070024463 0ustar erikadsouzastaff00000000000000from __future__ import print_function import json from watson_developer_cloud import AssistantV1 # If service instance provides API key authentication # assistant = AssistantV1( # version='2018-07-10', # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/assistant/api', # iam_apikey='iam_apikey') assistant = AssistantV1( username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD', ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/assistant/api', version='2018-07-10') ######################### # Workspaces ######################### create_workspace_data = { "name": "test_workspace", "description": "integration tests", "language": "en", "intents": [{ "intent": "hello", "description": "string", "examples": [{ "text": "good morning" }] }], "entities": [{ "entity": "pizza_toppings", "description": "Tasty pizza toppings", "metadata": { "property": "value" } }], "counterexamples": [{ "text": "string" }], "metadata": {}, } response = assistant.create_workspace( name=create_workspace_data['name'], description=create_workspace_data['description'], language='en', intents=create_workspace_data['intents'], entities=create_workspace_data['entities'], counterexamples=create_workspace_data['counterexamples'], metadata=create_workspace_data['metadata']).get_result() print(json.dumps(response, indent=2)) workspace_id = response['workspace_id'] print('Workspace id {0}'.format(workspace_id)) response = assistant.get_workspace( workspace_id=workspace_id, export=True).get_result() print(json.dumps(response, indent=2)) # message response = assistant.message( workspace_id=workspace_id, input={ 'text': 'What\'s the weather like?' }, context={ 'metadata': { 'deployment': 'myDeployment' } }).get_result() print(json.dumps(response, indent=2)) response = assistant.list_workspaces().get_result() print(json.dumps(response, indent=2)) response = assistant.update_workspace( workspace_id=workspace_id, description='Updated test workspace.').get_result() print(json.dumps(response, indent=2)) # see cleanup section below for delete_workspace example ######################### # Intents ######################### examples = [{"text": "good morning"}] response = assistant.create_intent( workspace_id=workspace_id, intent='test_intent', description='Test intent.', examples=examples).get_result() print(json.dumps(response, indent=2)) response = assistant.get_intent( workspace_id=workspace_id, intent='test_intent', export=True).get_result() print(json.dumps(response, indent=2)) response = assistant.list_intents( workspace_id=workspace_id, export=True).get_result() print(json.dumps(response, indent=2)) response = assistant.update_intent( workspace_id=workspace_id, intent='test_intent', new_intent='updated_test_intent', new_description='Updated test intent.').get_result() print(json.dumps(response, indent=2)) # see cleanup section below for delete_intent example ######################### # Examples ######################### response = assistant.create_example( workspace_id=workspace_id, intent='updated_test_intent', text='Gimme a pizza with pepperoni').get_result() print(json.dumps(response, indent=2)) response = assistant.get_example( workspace_id=workspace_id, intent='updated_test_intent', text='Gimme a pizza with pepperoni').get_result() print(json.dumps(response, indent=2)) response = assistant.list_examples( workspace_id=workspace_id, intent='updated_test_intent').get_result() print(json.dumps(response, indent=2)) response = assistant.update_example( workspace_id=workspace_id, intent='updated_test_intent', text='Gimme a pizza with pepperoni', new_text='Gimme a pizza with pepperoni').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_example( workspace_id=workspace_id, intent='updated_test_intent', text='Gimme a pizza with pepperoni').get_result() print(json.dumps(response, indent=2)) ######################### # Counter Examples ######################### response = assistant.create_counterexample( workspace_id=workspace_id, text='I want financial advice today.').get_result() print(json.dumps(response, indent=2)) response = assistant.get_counterexample( workspace_id=workspace_id, text='I want financial advice today.').get_result() print(json.dumps(response, indent=2)) response = assistant.list_counterexamples( workspace_id=workspace_id).get_result() print(json.dumps(response, indent=2)) response = assistant.update_counterexample( workspace_id=workspace_id, text='I want financial advice today.', new_text='I want financial advice today.').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_counterexample( workspace_id=workspace_id, text='I want financial advice today.').get_result() print(json.dumps(response, indent=2)) ######################### # Entities ######################### values = [{"value": "juice"}] response = assistant.create_entity( workspace_id=workspace_id, entity='test_entity', description='A test entity.', values=values).get_result() print(json.dumps(response, indent=2)) entities = [{ 'entity': 'pattern_entity', 'values': [{ 'value': 'value0', 'patterns': ['\\d{6}\\w{1}\\d{7}'], 'value_type': 'patterns' }, { 'value': 'value1', 'patterns': ['[-9][0-9][0-9][0-9][0-9]~! [1-9][1-9][1-9][1-9][1-9][1-9]'], 'value_type': 'patterns' }, { 'value': 'value2', 'patterns': ['[a-z-9]{17}'], 'value_type': 'patterns' }, { 'value': 'value3', 'patterns': [ '\\d{3}(\\ |-)\\d{3}(\\ |-)\\d{4}', '\\(\\d{3}\\)(\\ |-)\\d{3}(\\ |-)\\d{4}' ], 'value_type': 'patterns' }, { 'value': 'value4', 'patterns': ['\\b\\d{5}\\b'], 'value_type': 'patterns' }] }] response = assistant.create_entity( workspace_id, entity=entities[0]['entity'], values=entities[0]['values']).get_result() print(json.dumps(response, indent=2)) response = assistant.get_entity( workspace_id=workspace_id, entity=entities[0]['entity'], export=True).get_result() print(json.dumps(response, indent=2)) response = assistant.list_entities(workspace_id=workspace_id).get_result() print(json.dumps(response, indent=2)) response = assistant.update_entity( workspace_id=workspace_id, entity='test_entity', new_description='An updated test entity.').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_entity( workspace_id=workspace_id, entity='test_entity').get_result() print(json.dumps(response, indent=2)) ######################### # Synonyms ######################### values = [{"value": "orange juice"}] assistant.create_entity(workspace_id, 'beverage', values=values).get_result() response = assistant.create_synonym(workspace_id, 'beverage', 'orange juice', 'oj').get_result() print(json.dumps(response, indent=2)) response = assistant.get_synonym(workspace_id, 'beverage', 'orange juice', 'oj').get_result() print(json.dumps(response, indent=2)) response = assistant.list_synonyms(workspace_id, 'beverage', 'orange juice').get_result() print(json.dumps(response, indent=2)) response = assistant.update_synonym(workspace_id, 'beverage', 'orange juice', 'oj', 'OJ').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_synonym(workspace_id, 'beverage', 'orange juice', 'OJ').get_result() print(json.dumps(response, indent=2)) assistant.delete_entity(workspace_id, 'beverage').get_result() ######################### # Values ######################### assistant.create_entity(workspace_id, 'test_entity').get_result() response = assistant.create_value(workspace_id, 'test_entity', 'test').get_result() print(json.dumps(response, indent=2)) response = assistant.get_value(workspace_id, 'test_entity', 'test').get_result() print(json.dumps(response, indent=2)) response = assistant.list_values(workspace_id, 'test_entity').get_result() print(json.dumps(response, indent=2)) response = assistant.update_value(workspace_id, 'test_entity', 'test', 'example').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_value(workspace_id, 'test_entity', 'example').get_result() print(json.dumps(response, indent=2)) assistant.delete_entity(workspace_id, 'test_entity').get_result() ######################### # Dialog nodes ######################### create_dialog_node = { "dialog_node": "greeting", "description": "greeting messages", "actions": [{ "name": "hello", "type": "client", "parameters": {}, "result_variable": "string", "credentials": "string" }] } response = assistant.create_dialog_node( workspace_id, create_dialog_node['dialog_node'], create_dialog_node['description'], actions=create_dialog_node['actions']).get_result() print(json.dumps(response, indent=2)) response = assistant.get_dialog_node( workspace_id, create_dialog_node['dialog_node']).get_result() print(json.dumps(response, indent=2)) response = assistant.list_dialog_nodes(workspace_id).get_result() print(json.dumps(response, indent=2)) response = assistant.update_dialog_node( workspace_id, create_dialog_node['dialog_node'], new_dialog_node='updated_node').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_dialog_node(workspace_id, 'updated_node').get_result() print(json.dumps(response, indent=2)) ######################### # Logs ######################### response = assistant.list_logs(workspace_id=workspace_id).get_result() print(json.dumps(response, indent=2)) ######################### # Clean-up ######################### response = assistant.delete_intent( workspace_id=workspace_id, intent='updated_test_intent').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_workspace(workspace_id=workspace_id).get_result() print(json.dumps(response, indent=2)) watson-developer-cloud-2.10.1/examples/personality_insights_v3.py0000755000076500000240000000335513451407070026734 0ustar erikadsouzastaff00000000000000""" The example returns a JSON response whose content is the same as that in ../resources/personality-v3-expect2.txt """ from __future__ import print_function import json from os.path import join, dirname from watson_developer_cloud import PersonalityInsightsV3 import csv # # If service instance provides API key authentication # service = PersonalityInsightsV3( # version='2017-10-13', # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/personality-insights/api', # iam_apikey='your_apikey') service = PersonalityInsightsV3( version='2017-10-13', ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/personality-insights/api', username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') ############################ # Profile with JSON output # ############################ with open(join(dirname(__file__), '../resources/personality-v3.json')) as \ profile_json: profile = service.profile( profile_json.read(), content_type='application/json', raw_scores=True, consumption_preferences=True).get_result() print(json.dumps(profile, indent=2)) ########################### # Profile with CSV output # ########################### with open(join(dirname(__file__), '../resources/personality-v3.json')) as \ profile_json: response = service.profile( profile_json.read(), content_type='application/json', accept="text/csv", csv_headers=True).get_result() profile = response.content cr = csv.reader(profile.splitlines()) my_list = list(cr) for row in my_list: print(row) watson-developer-cloud-2.10.1/setup.cfg0000644000076500000240000000004613451440673021471 0ustar erikadsouzastaff00000000000000[egg_info] tag_build = tag_date = 0