diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 3b4781f21..4eca3e4cf 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.3.0 +current_version = 7.0.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index dad38e7f5..4849b2f45 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -21,11 +21,11 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.7', '3.8', '3.9'] + python-version: ['3.9', '3.10', '3.11'] os: [ubuntu-latest, windows-latest] exclude: - os: windows-latest - python-version: '3.7' + python-version: '3.9' steps: - uses: actions/checkout@v2 @@ -45,33 +45,33 @@ jobs: pip3 install -r requirements.txt --use-deprecated=legacy-resolver pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver pip3 install --editable . --use-deprecated=legacy-resolver - - name: Execute Python 3.7 unit tests - if: matrix.python-version == '3.7' + - name: Execute Python 3.9 unit tests + if: matrix.python-version == '3.9' run: | pip3 install -U python-dotenv py.test test/unit - - name: Execute Python 3.8 unit tests (windows) - if: matrix.python-version == '3.8' && matrix.os == 'windows-latest' + - name: Execute Python 3.10 unit tests (windows) + if: matrix.python-version == '3.10' && matrix.os == 'windows-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - - name: Execute Python 3.8 unit tests (ubuntu) - if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.10 unit tests (ubuntu) + if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 --cov=ibm_watson - - name: Execute Python 3.9 unit tests (windows) - if: matrix.python-version == '3.9' && matrix.os == 'windows-latest' + - name: Execute Python 3.11 unit tests (windows) + if: matrix.python-version == '3.11' && matrix.os == 'windows-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - - name: Execute Python 3.9 unit tests (ubuntu) - if: matrix.python-version == '3.9' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.11 unit tests (ubuntu) + if: matrix.python-version == '3.11' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - name: Upload coverage to Codecov - if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' + if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' uses: codecov/codecov-action@v1 with: name: py${{ matrix.python-version }}-${{ matrix.os }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d8bae9d26..16f3dda0c 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -29,12 +29,12 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: '3.9' + python-version: '3.11' - name: Setup Node uses: actions/setup-node@v1 with: - node-version: 14 + node-version: 18 - name: Install Semantic Release dependencies run: | @@ -74,4 +74,4 @@ jobs: uses: pypa/gh-action-pypi-publish@v1.4.2 # Try to update version tag every release with: password: ${{ secrets.PYPI_TOKEN }} - repository_url: https://upload.pypi.org/legacy/ # This must be changed if testing deploys to test.pypi.org \ No newline at end of file + repository_url: https://upload.pypi.org/legacy/ # This must be changed if testing deploys to test.pypi.org diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 059bf7220..05e66e579 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -15,7 +15,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ["3.8"] + python-version: ["3.11"] os: [ubuntu-latest] steps: diff --git a/.secrets.baseline b/.secrets.baseline index a9c0826d5..400f98f69 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "package-lock.json|^.secrets.baseline$", "lines": null }, - "generated_at": "2022-03-21T19:21:18Z", + "generated_at": "2023-03-17T19:47:10Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -25,9 +25,7 @@ "name": "CloudantDetector" }, { - "name": "Db2Detector" - }, - { + "ghe_instance": "github.ibm.com", "name": "GheDetector" }, { @@ -67,22 +65,12 @@ } ], "results": { - ".github/workflows/deploy.yml": [ - { - "hashed_secret": "51543e129a641c2ece91b32b5bbeaa704dbfe764", - "is_secret": false, - "is_verified": false, - "line_number": 76, - "type": "DB2 Credentials", - "verified_result": null - } - ], "README.md": [ { "hashed_secret": "d9e9019d9eb455a3d72a3bc252c26927bb148a10", "is_secret": false, "is_verified": false, - "line_number": 132, + "line_number": 119, "type": "Secret Keyword", "verified_result": null }, @@ -90,23 +78,7 @@ "hashed_secret": "32e8612d8ca77c7ea8374aa7918db8e5df9252ed", "is_secret": false, "is_verified": false, - "line_number": 174, - "type": "Secret Keyword", - "verified_result": null - }, - { - "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", - "is_secret": false, - "is_verified": false, - "line_number": 228, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", - "is_secret": false, - "is_verified": false, - "line_number": 228, + "line_number": 163, "type": "Secret Keyword", "verified_result": null } @@ -123,34 +95,18 @@ ], "ibm_watson/discovery_v1.py": [ { - "hashed_secret": "3442496b96dd01591a8cd44b1eec1368ab728aba", - "is_secret": false, - "is_verified": false, - "line_number": 4723, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "b16c7ac6faff07d7e255da685e52bd66d3bf1575", - "is_secret": false, - "is_verified": false, - "line_number": 4781, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", "is_secret": false, "is_verified": false, - "line_number": 4828, - "type": "DB2 Credentials", + "line_number": 5220, + "type": "Secret Keyword", "verified_result": null }, { - "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", + "hashed_secret": "fdee05598fdd57ff8e9ae29e92c25a04f2c52fa6", "is_secret": false, "is_verified": false, - "line_number": 4967, + "line_number": 5221, "type": "Secret Keyword", "verified_result": null } @@ -171,32 +127,52 @@ "is_secret": false, "is_verified": false, "line_number": 168, - "type": "DB2 Credentials", + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/unit/test_assistant_v1.py": [ + { + "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", + "is_secret": false, + "is_verified": false, + "line_number": 7661, + "type": "Secret Keyword", "verified_result": null }, { - "hashed_secret": "b60d121b438a380c343d5ec3c2037564b82ffef3", + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 168, + "line_number": 11192, "type": "Secret Keyword", "verified_result": null } ], - "test/unit/test_discovery_v1.py": [ + "test/unit/test_assistant_v2.py": [ { - "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", "is_secret": false, "is_verified": false, - "line_number": 6789, - "type": "DB2 Credentials", + "line_number": 1333, + "type": "Secret Keyword", "verified_result": null }, + { + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", + "is_secret": false, + "is_verified": false, + "line_number": 6510, + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/unit/test_discovery_v1.py": [ { "hashed_secret": "8318df9ecda039deac9868adf1944a29a95c7114", "is_secret": false, "is_verified": false, - "line_number": 6789, + "line_number": 6733, "type": "Secret Keyword", "verified_result": null }, @@ -204,7 +180,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 7961, + "line_number": 7882, "type": "Secret Keyword", "verified_result": null }, @@ -212,7 +188,7 @@ "hashed_secret": "b8e758b5ad59a72f146fcf065239d5c7b695a39a", "is_secret": false, "is_verified": false, - "line_number": 10241, + "line_number": 10064, "type": "Hex High Entropy String", "verified_result": null } @@ -222,13 +198,13 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 418, + "line_number": 411, "type": "Secret Keyword", "verified_result": null } ] }, - "version": "0.13.1+ibm.26.dss", + "version": "0.13.1+ibm.56.dss", "word_list": { "file": null, "hash": null diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85c67d0af..c431459c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ If you want to contribute to the repository, here's a quick guide: - Only use spaces for indentation. - Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. - Check for unnecessary whitespace with `git diff --check` before committing. - - Make sure your code supports Python 3.7, 3.8, 3.9. You can use `pyenv` and `tox` for this + - Make sure your code supports Python 3.9, 3.10, 3.11. You can use `pyenv` and `tox` for this 1. Make the test pass 1. Commit your changes diff --git a/MIGRATION-V4.md b/MIGRATION-V4.md deleted file mode 100644 index 52fc40182..000000000 --- a/MIGRATION-V4.md +++ /dev/null @@ -1,215 +0,0 @@ -Here are simple steps to move from `v3.0.0` to `v4.0.0`. Note that `v4.0,0` supports only python `3.5` and above - -## AUTHENTICATION MECHANISM -The constructor no longer accepts individual credentials like `iam_apikey`, etc. We initialize authenticators from the [core](https://github.com/IBM/python-sdk-core). The core supports various authentication mechanisms, choose the one appropriate to your instance and use case. - -For example, to pass a IAM apikey: -#### Before -```python -from ibm_watson import MyService - -service = MyService( - iam_apikey='{apikey}', - url='{url}' -) -``` - -#### After(V4.0) -```python -from ibm_watson import MyService -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('{apikey}') -service = MyService( - authenticator=authenticator -) -service.set_service_url('{url}') -``` - -There are 5 authentication variants supplied in the SDK (shown below), and it's possible now to create your own authentication implementation if you need something specific by implementing the Authenticator implementation. - -#### BasicAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -authenticator = BasicAuthenticator(, ) -service = MyService(authenticator=authenticator) -``` - -#### BearerTokenAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator - -authenticator = BearerTokenAuthenticator() -service = MyService(authenticator=authenticator) - -# can set bearer token -service.get_authenticator().set_bearer_token('xxx'); -``` - -#### CloudPakForDataAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator - -authenticator = CloudPakForDataAuthenticator( - 'my_username', - 'my_password', - 'https://my-cp4d-url', - disable_ssl_verification=True) -service = MyService(authenticator=authenticator) -``` - -#### IAMAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('my_apikey') -service = MyService(authenticator=authenticator) -``` - -#### NoAuthAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator - -authenticator = NoAuthAuthenticator() -service = MyService(authenticator=authenticator) -``` - -#### Creating an Authenticator from Environmental Configuration -```python -from ibm_cloud_sdk_core import get_authenticator_from_environment - -authenticator = get_authenticator_from_environment('Assistant') -service = MyService(authenticator=authenticator) -``` - -## SETTING THE SERVICE URL -We can set the service url using `set_service_url()` or from external configurations. - -#### Before -```python -service = MyService( - iam_apikey='{apikey}', - url='{url}' # <= here -) -``` - -#### After(V4.0) -```python -service = MyService( - authenticator=authenticator, -) -service.set_service_url('{url}') -``` - -OR, pass from external configurations like environment variable -```bash -export MY_SERVICE_URL="" -``` - -## METHOD OPTIONAL PARAM -The method params which are optional would need to be specified by name rather than position. For example - -#### Before -The list_workspaces with page_limit as 10 was: - -```python -assistant_service.list_workspaces(10) -``` - -#### After(V4.0) -We need to specify the optional param name: - -```python -assistant_service.list_workspaces(page_limit=10) -``` - -## DISABLING SSL VERIFICATION -#### Before -```python -service.disable_ssl_verification(True) -``` - -#### After(v4.0) -```python -service.set_disable_ssl_verification(True) -``` - -## SUPPORT FOR CONSTANTS -Constants for methods and models are shown in the form of Enums - -## SUPPORT FOR PYTHON 2.7 and 3.4 AND BELOW DROPPED -The SDK no longer supports Pyhton versions 2.7 and <=3.4. - -## SERVICE CHANGES -#### AssistantV1 -* `include_count` is no longer a parameter of the list_workspaces() method -* `include_count` is no longer a parameter of the list_intents() method -* `include_count` is no longer a parameter of the list_examples() method -* `include_count` is no longer a parameter of the list_counterexamples() method -* `include_count` is no longer a parameter of the list_entities() method -* `include_count` is no longer a parameter of the list_values() method -* `include_count` is no longer a parameter of the list_synonyms() method -* `include_count` is no longer a parameter of the list_dialog_nodes() method -* `value_type` was renamed to `type` in the create_value() method -* `new_value_type` was renamed to `new_type` in the update_value() method -* `node_type` was renamed to `type` in the create_dialog_node() method -* `new_node_type` was renamed to `new_type` in the update_dialog_node() method -* `value_type` was renamed to `type` in the CreateValue model -* `node_type` was renamed to `type` in the DialogNode model -* `action_type` was renamed to `type` in the DialogNodeAction model -* `query_type` property was added to the DialogNodeOutputGeneric model -* `query` property was added to the DialogNodeOutputGeneric model -* `filter` property was added to the DialogNodeOutputGeneric model -* `discovery_version` property was added to the DialogNodeOutputGeneric model -* LogMessage model no longer has `_additionalProperties` -* `DialogRuntimeResponseGeneric` was renamed to `RuntimeResponseGeneric` -* RuntimeEntity model no longer has `_additionalProperties` -* RuntimeIntent model no longer has `_additionalProperties` -* `value_type` was renamed to `type` in the Value model - -#### AssistantV2 -* `action_type` was renamed to `type` in the DialogNodeAction model -* DialogRuntimeResponseGeneric was renamed to RuntimeResponseGeneric - -#### Compare and Comply -* `convert_to_html()` method does not require a filename parameter - -#### DiscoveryV1 -* `return_fields` was renamed to `return_` in the query() method -* `logging_opt_out` was renamed to `x_watson_logging_opt_out` in the query() method -* `spelling_suggestions` was added to the query() method -* `collection_ids` is no longer a parameter of the query() method -* `return_fields` was renamed to `return_` in the QueryNotices() method -* `logging_opt_out` was renamed to `x_watson_logging_opt_out` in the federated_query() method -* `collection_ids` is now required in the federated_query() method -* `collection_ids` changed position in the federated_query() method -* `return_fields` was renamed to `return_` in the federated_query() method -* `return_fields` was renamed to `return_` in the federated_query_notices() method -* `enrichment_name` was renamed to `enrichment` in the Enrichment model -* `field_type` was renamed to `type` in the Field model -* `field_name` was renamed to `field` in the Field model -* test_configuration_in_environment() method was removed -* query_entities() method was removed -* query_relations() method was removed - -#### Language Translator V3 -* `default_models` was renamed to `default` in the list_models() method -* `translation_output` was renamed to `translation` in the Translation model - -#### Natural Language Classifier V1 -* `metadata` was renamed to `training_metadata` in the `create_classifier()` method - -#### Speech to Text V1 -* `final_results` was renamed to `final` in the SpeakerLabelsResult model -* `final_results` was renamed to `final` in the SpeechRecognitionResult model - -#### Visual Recognition V3 -* `detect_faces()` method was removed -* `class_name` was renamed to `class_` in the ClassResult model -* `class_name` was renamed to `class_` in the ModelClass model - -#### Visual Recognition V4 -* New Service! - - diff --git a/MIGRATION-V5.md b/MIGRATION-V5.md deleted file mode 100644 index 88b36428f..000000000 --- a/MIGRATION-V5.md +++ /dev/null @@ -1,175 +0,0 @@ -## Python SDK V5 Migration guide - -### Service changes - -#### Assistant v1 - -* `include_count` is now a parameter of the `list_workspaces()` method -* `include_count` is now a parameter of the `list_intents()` method -* `include_count` is now a parameter of the `list_examples()` method -* `include_count` is now a parameter of the `list_counterexamples()` method -* `include_count` is now a parameter of the `list_entities()` method -* `include_count` is now a parameter of the `list_values()` method -* `include_count` is now a parameter of the `list_synonyms()` method -* `include_count` is now a parameter of the `list_dialogNodes()` method -* `context` type was changed from `dict` to `DialogNodeContext` in the `create_dialog_node()` method -* `new_context` type was changed from `dict` to `DialogNodeContext` in the `update_dialog_node()` method -* `bulk_classify()` method was addded - -##### Models Added - -`BulkClassifyOutput`, -`BulkClassifyResponse`, -`BulkClassifyUtterance`, -`DialogNodeContext`, -`DialogNodeOutputConnectToAgentTransferInfo`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeImage`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeOption`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypePause`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeText`, -`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, -`RuntimeResponseGenericRuntimeResponseTypeImage`, -`RuntimeResponseGenericRuntimeResponseTypeOption`, -`RuntimeResponseGenericRuntimeResponseTypePause`, -`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, -`RuntimeResponseGenericRuntimeResponseTypeText` - -##### Models Removed - -`DialogSuggestionOutput`, -`DialogSuggestionResponseGeneric` - -##### Model Properties Changed - -`DialogNode` -* `context` property type changed from `Dictionary` to `DialogNodeContext` - -`DialogNodeOutput` -* Added `Integrations` property with getter and setter - -`DialogNodeOutputGeneric`, `RuntimeResponseGeneric` -* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties - -`DialogSuggestion` -* `output` property type changed from `DialogSuggestionOutput` to `Dictionary` - -#### Assistant v2 - -* `bulk_classify()` method was addded - -##### Models Added - -`BulkClassifyOutput`, -`BulkClassifyResponse`, -`BulkClassifyUtterance`, -`DialogNodeOutputConnectToAgentTransferInfo`, -`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, -`RuntimeResponseGenericRuntimeResponseTypeImage`, -`RuntimeResponseGenericRuntimeResponseTypeOption`, -`RuntimeResponseGenericRuntimeResponseTypePause`, -`RuntimeResponseGenericRuntimeResponseTypeSearch`, -`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, -`RuntimeResponseGenericRuntimeResponseTypeText` - -##### Model Properties Changed - -`MessageContext`, `MessageContextStateless` -* `Skills` property type changed from `MessageContextSkills` to `Dictionary` - -`MessageContextSkill` -* `System` property type changed from `Dictionary` to `MessageContextSkillSystem` - -`RuntimeResponseGeneric` -* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties - -#### Compare Comply v1 - -* `before` and `after` parameters were removed from `list_feedback` method - -##### Model Properties Changed - -`Category`, `TypeLabel` -* Added `modification` property - -`OriginalLabelsOut`, `UpdatedLabelsOut` -* Removed `modification` property - -#### Discovery v1 - -No changes - -#### Discovery v2 - -##### Models Added - -`QueryResponsePassage` - -##### Models Removed - -`QueryNoticesResult` - -##### Model Properties Changed - -`QueryResponse` -* Added `Passages` property - -#### Language Translator v3 - -No changes - -#### Natural Language Classifier v1 - -No changes - -#### Natural Language Understanding v1 - -No changes - -#### Personality Insights - -No changes - -#### Speech To Text v1 - -No changes - -#### Text To Speech v1 - -* Renamed `CreateVoiceModel()` method to `CreateCustomModel()` - -* Renamed `ListVoiceModels()` method to `ListCustomModels()` - -* Renamed `UpdateVoiceModel()` method to `UpdateCustomModel()` - -* Renamed `GetVoiceModel()` method to `GetCustomModel()` - -* Renamed `DeleteVoiceModel()` method to `GetCustomModel()` - -##### Models Added - -`CustomModel`, -`CustomModels` - -##### Models Removed - -`VoiceModel`, -`VoiceModels` - -##### Model Properties Changed - -`Voice` -* Change return type of `customization` from `VoiceModel` to `CustomModel` - -#### Tone Analyzer v3 - -No changes - -#### Visual Recognition v3 - -No changes - -#### Visual Recognition v4 - -* Changed `start_time` and `end_time` parameter types from `string` to `date` in `get_training_usage()` method \ No newline at end of file diff --git a/MIGRATION-V7.md b/MIGRATION-V7.md new file mode 100644 index 000000000..765ac9ad7 --- /dev/null +++ b/MIGRATION-V7.md @@ -0,0 +1,55 @@ +# Upgrading to ibm-watson@8.0 + [Breaking Changes](#breaking-changes) + - [Breaking changes by service](#breaking-changes-by-service) + +- [New Features by Service](#new-features-by-service) + +### Breaking changes by service + +#### Assistant v2 +- Parameter `createSession` removed from `createSession` function +- Class `Environment` property `language` removed +- Class `EnvironmentReleaseReference` renamed to `BaseEnvironmentReleaseReference` +- Class `EnvironmentOrchestration` renamed to `BaseEnvironmentOrchestration` +- Class `SkillReference` renamed to `EnvironmentSkill` + +#### Discovery v2 +- Parameter `smartDocumentUnderstanding` removed from `createCollection` function +- Class `QueryResponsePassage` and `QueryResultPassage` property `confidence` removed +- Class `DocumentClassifierEnrichment` property `enrichmentId` is no longer an optional +- QueryAggregation classes restructured + +#### Natural Language Understanding +- All `sentiment_model` functions removed +- `create_classifications_model`, `update_classifications_model`, `create_categories_model`, and `update_categories_model` now require `training_data_content_type` + +#### Speech to Text +- `AR_AR_BROADBANDMODEL` model removed in favor of `AR_MS_BROADBANDMODEL` model + +### New Features by Service + +#### Assistant v2 +- `create_assistant` function +- `list_assistants` function +- `delete_assistant` function +- `update_environment` function +- `create_release` function +- `delete_release` function +- `get_skill` function +- `update_skill` function +- `export_skills` function +- `import_skills` function +- `import_skills_status` function +- Improved typing for `message` function call +See details of these functions on IBM's documentation site [here](https://cloud.ibm.com/apidocs/assistant-v2?code=python) + +#### Discovery v2 +- Aggregation types `QueryTopicAggregation` and `QueryTrendAggregation` added + +#### Speech to Text +- added `FR_CA_MULTIMEDIA`, `JA_JP_TELEPHONY`, `NL_NL_MULTIMEDIA`, `SV_SE_TELEPHONY` models + +#### Text to Speech +- added `EN_AU_HEIDIEXPRESSIVE`, `EN_AU_JACKEXPRESSIVE`, `EN_US_ALLISONEXPRESSIVE`, `EN_US_EMMAEXPRESSIVE`, `EN_US_LISAEXPRESSIVE`, `EN_US_MICHAELEXPRESSIVE`, `KO_KR_JINV3VOICE` +- Parameters `rate_percentage` and `pitch_percentage` added to `synthesize` function +See details of these new parameters on IBM's documentation site [here](https://cloud.ibm.com/apidocs/text-to-speech?code=python#synthesize) diff --git a/README.md b/README.md index 8fb71fc37..9733d0262 100755 --- a/README.md +++ b/README.md @@ -12,24 +12,6 @@ Python client library to quickly get started with the various [Watson APIs][wdc] services. -## Announcements - -### Tone Analyzer Deprecation - -As of this major release, 6.0.0, the Tone Analyzer api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to Tone Analyzer until its final deprecation, you will have to use a previous version. - -On 24 February 2022, IBM announced the deprecation of the Tone Analyzer service. The service will no longer be available as of 24 February 2023. As of 24 February 2022, you will not be able to create new instances. Existing instances will be supported until 24 February 2023. - -As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud. With Natural Language Understanding, tone analysis is done by using a pre-built classifications model, which provides an easy way to detect language tones in written text. For more information, see [Migrating from Watson Tone Analyzer Customer Engagement endpoint to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-tone_analytics). - -### Natural Language Classifier Deprecation - -As of this major release, 6.0.0, the NLC api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to NLC until its final deprecation, you will have to use a previous version. - -On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. - -As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax, along with advanced multi-label text classification capabilities, to provide even richer insights for your business or industry. For more information, see [Migrating to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). - ## Before you begin - You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above @@ -219,64 +201,12 @@ discovery.set_service_url('') ## Python version -Tested on Python 3.5, 3.6, and 3.7. +Tested on Python 3.9, 3.10, and 3.11. ## Questions If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). -## Changes for v1.0 - -Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v2.0 - -`DetailedResponse` which contains the result, headers and HTTP status code is now the default response for all methods. - -```python -from ibm_watson import AssistantV1 - -assistant = AssistantV1( - username='xxx', - password='yyy', - url='', - version='2018-07-10') - -response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}) -print(response.get_result()) -print(response.get_headers()) -print(response.get_status_code()) -``` - -See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v3.0 - -The SDK is generated using OpenAPI Specification(OAS3). Changes are basic reordering of parameters in function calls. - -The package is renamed to ibm_watson. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v4.0 - -Authenticator variable indicates the type of authentication to be used. - -```python -from ibm_watson import AssistantV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', - authenticator=authenticator) -assistant.set_service_url('') -``` - -For more information, follow the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md) - -## Migration - -To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md). - ## Configuring the http client (Supported from v1.1.0) To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://2.python-requests.org/en/master/api/#requests.request) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance @@ -558,33 +488,13 @@ HTTPConnection.debuglevel = 1 - `python_dateutil` >= 2.5.3 - [responses] for testing - Following for web sockets support in speech to text - - `websocket-client` 0.48.0 -- `ibm_cloud_sdk_core` == 1.0.0 + - `websocket-client` 1.1.0 +- `ibm_cloud_sdk_core` >= 3.16.2 ## Contributing See [CONTRIBUTING.md][contributing]. -## Featured Projects - -Here are some projects that have been using the SDK: - -- [NLC ICD-10 Classifier](https://github.com/IBM/nlc-icd10-classifier) -- [Cognitive Moderator Service](https://github.com/IBM/cognitive-moderator-service) - -We'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it. - ## License This library is licensed under the [Apache 2.0 license][license]. - -[wdc]: http://www.ibm.com/watson/developercloud/ -[ibm_cloud]: https://cloud.ibm.com/ -[watson-dashboard]: https://cloud.ibm.com/catalog?category=ai -[responses]: https://github.com/getsentry/responses -[requests]: http://docs.python-requests.org/en/latest/ -[examples]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples -[contributing]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md -[license]: http://www.apache.org/licenses/LICENSE-2.0 -[vcap_services]: https://cloud.ibm.com/docs/watson?topic=watson-vcapServices -[ibm-cloud-onboarding]: https://cloud.ibm.com/registration?target=/developer/watson&cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Python diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index bbdb45f5b..d0a1620e5 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -138,7 +138,7 @@ def message(self, :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if input is not None: input = convert_model(input) @@ -158,7 +158,7 @@ def message(self, params = { 'version': self.version, - 'nodes_visited_details': nodes_visited_details + 'nodes_visited_details': nodes_visited_details, } data = { @@ -168,7 +168,7 @@ def message(self, 'alternate_intents': alternate_intents, 'context': context, 'output': output, - 'user_id': user_id + 'user_id': user_id, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -176,6 +176,7 @@ def message(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -216,7 +217,7 @@ def bulk_classify(self, :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if input is not None: input = [convert_model(x) for x in input] @@ -226,15 +227,20 @@ def bulk_classify(self, operation_id='bulk_classify') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input} + data = { + 'input': input, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -298,11 +304,12 @@ def list_workspaces(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/workspaces' @@ -334,6 +341,8 @@ def create_workspace(self, Create a workspace based on component objects. You must provide workspace components defining the content of the new workspace. + **Note:** The new workspace data cannot be larger than 1.5 MB. For larger + requests, use the **Create workspace asynchronously** method. :param str name: (optional) The name of the workspace. This string cannot contain carriage return, newline, or tab characters. @@ -381,7 +390,10 @@ def create_workspace(self, operation_id='create_workspace') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'name': name, @@ -394,7 +406,7 @@ def create_workspace(self, 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -402,6 +414,7 @@ def create_workspace(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/workspaces' @@ -442,7 +455,7 @@ def get_workspace(self, :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -454,11 +467,12 @@ def get_workspace(self, 'version': self.version, 'export': export, 'include_audit': include_audit, - 'sort': sort + 'sort': sort, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -495,6 +509,8 @@ def update_workspace(self, Update an existing workspace with new or modified data. You must provide component objects defining the content of the updated workspace. + **Note:** The new workspace data cannot be larger than 1.5 MB. For larger + requests, use the **Update workspace asynchronously** method. :param str workspace_id: Unique identifier of the workspace. :param str name: (optional) The name of the workspace. This string cannot @@ -534,7 +550,7 @@ def update_workspace(self, :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if dialog_nodes is not None: dialog_nodes = [convert_model(x) for x in dialog_nodes] @@ -557,7 +573,7 @@ def update_workspace(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -571,7 +587,7 @@ def update_workspace(self, 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -579,6 +595,7 @@ def update_workspace(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -606,7 +623,7 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -614,10 +631,13 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: operation_id='delete_workspace') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -632,6 +652,299 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response + def create_workspace_async( + self, + *, + name: str = None, + description: str = None, + language: str = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + webhooks: List['Webhook'] = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + **kwargs) -> DetailedResponse: + """ + Create workspace asynchronously. + + Create a workspace asynchronously based on component objects. You must provide + workspace components defining the content of the new workspace. + A successful call to this method only initiates asynchronous creation of the + workspace. The new workspace is not available until processing completes. To check + the status of the asynchronous operation, use the **Get information about a + workspace** method. + + :param str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param List[Webhook] webhooks: (optional) + :param List[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param List[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if dialog_nodes is not None: + dialog_nodes = [convert_model(x) for x in dialog_nodes] + if counterexamples is not None: + counterexamples = [convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = convert_model(system_settings) + if webhooks is not None: + webhooks = [convert_model(x) for x in webhooks] + if intents is not None: + intents = [convert_model(x) for x in intents] + if entities is not None: + entities = [convert_model(x) for x in entities] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace_async') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, + 'metadata': metadata, + 'learning_opt_out': learning_opt_out, + 'system_settings': system_settings, + 'webhooks': webhooks, + 'intents': intents, + 'entities': entities, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v1/workspaces_async' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def update_workspace_async( + self, + workspace_id: str, + *, + name: str = None, + description: str = None, + language: str = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + webhooks: List['Webhook'] = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + append: bool = None, + **kwargs) -> DetailedResponse: + """ + Update workspace asynchronously. + + Update an existing workspace asynchronously with new or modified data. You must + provide component objects defining the content of the updated workspace. + A successful call to this method only initiates an asynchronous update of the + workspace. The updated workspace is not available until processing completes. To + check the status of the asynchronous operation, use the **Get information about a + workspace** method. + + :param str workspace_id: Unique identifier of the workspace. + :param str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param List[Webhook] webhooks: (optional) + :param List[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param List[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :param bool append: (optional) Whether the new data is to be appended to + the existing data in the object. If **append**=`false`, elements included + in the new data completely replace the corresponding existing elements, + including all subelements. For example, if the new data for a workspace + includes **entities** and **append**=`false`, all existing entities in the + workspace are discarded and replaced with the new entities. + If **append**=`true`, existing elements are preserved, and the new elements + are added. If any elements in the new data collide with existing elements, + the update request fails. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if not workspace_id: + raise ValueError('workspace_id must be provided') + if dialog_nodes is not None: + dialog_nodes = [convert_model(x) for x in dialog_nodes] + if counterexamples is not None: + counterexamples = [convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = convert_model(system_settings) + if webhooks is not None: + webhooks = [convert_model(x) for x in webhooks] + if intents is not None: + intents = [convert_model(x) for x in intents] + if entities is not None: + entities = [convert_model(x) for x in entities] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace_async') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'append': append, + } + + data = { + 'name': name, + 'description': description, + 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, + 'metadata': metadata, + 'learning_opt_out': learning_opt_out, + 'system_settings': system_settings, + 'webhooks': webhooks, + 'intents': intents, + 'entities': entities, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces_async/{workspace_id}'.format(**path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def export_workspace_async(self, + workspace_id: str, + *, + include_audit: bool = None, + sort: str = None, + verbose: bool = None, + **kwargs) -> DetailedResponse: + """ + Export workspace asynchronously. + + Export the entire workspace asynchronously, including all workspace content. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. After the initial + request is submitted, you can continue to poll by calling the same request again + and checking the value of the **status** property. When processing has completed, + the request returns the exported JSON data. Remember that the usual rate limits + apply. + + :param str workspace_id: Unique identifier of the workspace. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param str sort: (optional) Indicates how the returned workspace data will + be sorted. Specify `sort=stable` to sort all workspace objects by unique + identifier, in ascending alphabetical order. + :param bool verbose: (optional) Whether the response should include the + `counts` property, which indicates how many of each component (such as + intents and entities) the workspace contains. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if not workspace_id: + raise ValueError('workspace_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='export_workspace_async') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + 'sort': sort, + 'verbose': verbose, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces_async/{workspace_id}/export'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + ######################### # Intents ######################### @@ -674,7 +987,7 @@ def list_intents(self, :rtype: DetailedResponse with `dict` result representing a `IntentCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -689,11 +1002,12 @@ def list_intents(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -740,7 +1054,7 @@ def create_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') @@ -752,12 +1066,15 @@ def create_intent(self, operation_id='create_intent') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'intent': intent, 'description': description, - 'examples': examples + 'examples': examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -765,6 +1082,7 @@ def create_intent(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -805,9 +1123,9 @@ def get_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -818,11 +1136,12 @@ def get_intent(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -883,9 +1202,9 @@ def update_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') if new_examples is not None: new_examples = [convert_model(x) for x in new_examples] @@ -898,13 +1217,13 @@ def update_intent(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { 'intent': new_intent, 'description': new_description, - 'examples': new_examples + 'examples': new_examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -912,6 +1231,7 @@ def update_intent(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -942,9 +1262,9 @@ def delete_intent(self, workspace_id: str, intent: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -952,10 +1272,13 @@ def delete_intent(self, workspace_id: str, intent: str, operation_id='delete_intent') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1011,9 +1334,9 @@ def list_examples(self, :rtype: DetailedResponse with `dict` result representing a `ExampleCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1027,11 +1350,12 @@ def list_examples(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1077,9 +1401,9 @@ def create_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') if text is None: raise ValueError('text must be provided') @@ -1091,15 +1415,22 @@ def create_example(self, operation_id='create_example') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': text, 'mentions': mentions} + data = { + 'text': text, + 'mentions': mentions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1138,11 +1469,11 @@ def get_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1150,10 +1481,14 @@ def get_example(self, operation_id='get_example') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1201,11 +1536,11 @@ def update_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') if new_mentions is not None: new_mentions = [convert_model(x) for x in new_mentions] @@ -1215,15 +1550,22 @@ def update_example(self, operation_id='update_example') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': new_text, 'mentions': new_mentions} + data = { + 'text': new_text, + 'mentions': new_mentions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1255,11 +1597,11 @@ def delete_example(self, workspace_id: str, intent: str, text: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1267,10 +1609,13 @@ def delete_example(self, workspace_id: str, intent: str, text: str, operation_id='delete_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1324,7 +1669,7 @@ def list_counterexamples(self, :rtype: DetailedResponse with `dict` result representing a `CounterexampleCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1338,11 +1683,12 @@ def list_counterexamples(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1384,7 +1730,7 @@ def create_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text must be provided') @@ -1394,15 +1740,21 @@ def create_counterexample(self, operation_id='create_counterexample') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': text} + data = { + 'text': text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1441,9 +1793,9 @@ def get_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1451,10 +1803,14 @@ def get_counterexample(self, operation_id='get_counterexample') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1497,9 +1853,9 @@ def update_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1507,15 +1863,21 @@ def update_counterexample(self, operation_id='update_counterexample') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': new_text} + data = { + 'text': new_text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1548,9 +1910,9 @@ def delete_counterexample(self, workspace_id: str, text: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1558,10 +1920,13 @@ def delete_counterexample(self, workspace_id: str, text: str, operation_id='delete_counterexample') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1619,7 +1984,7 @@ def list_entities(self, :rtype: DetailedResponse with `dict` result representing a `EntityCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1634,11 +1999,12 @@ def list_entities(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1692,7 +2058,7 @@ def create_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') @@ -1704,14 +2070,17 @@ def create_entity(self, operation_id='create_entity') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'entity': entity, 'description': description, 'metadata': metadata, 'fuzzy_match': fuzzy_match, - 'values': values + 'values': values, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1719,6 +2088,7 @@ def create_entity(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1759,9 +2129,9 @@ def get_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1772,11 +2142,12 @@ def get_entity(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1842,9 +2213,9 @@ def update_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') if new_values is not None: new_values = [convert_model(x) for x in new_values] @@ -1857,7 +2228,7 @@ def update_entity(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -1865,7 +2236,7 @@ def update_entity(self, 'description': new_description, 'metadata': new_metadata, 'fuzzy_match': new_fuzzy_match, - 'values': new_values + 'values': new_values, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1873,6 +2244,7 @@ def update_entity(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1903,9 +2275,9 @@ def delete_entity(self, workspace_id: str, entity: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1913,10 +2285,13 @@ def delete_entity(self, workspace_id: str, entity: str, operation_id='delete_entity') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1962,9 +2337,9 @@ def list_mentions(self, :rtype: DetailedResponse with `dict` result representing a `EntityMentionCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1975,11 +2350,12 @@ def list_mentions(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2039,9 +2415,9 @@ def list_values(self, :rtype: DetailedResponse with `dict` result representing a `ValueCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2056,11 +2432,12 @@ def list_values(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2120,9 +2497,9 @@ def create_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') @@ -2132,14 +2509,17 @@ def create_value(self, operation_id='create_value') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'value': value, 'metadata': metadata, 'type': type, 'synonyms': synonyms, - 'patterns': patterns + 'patterns': patterns, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2147,6 +2527,7 @@ def create_value(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2190,11 +2571,11 @@ def get_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2205,11 +2586,12 @@ def get_value(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2284,11 +2666,11 @@ def update_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2299,7 +2681,7 @@ def update_value(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -2307,7 +2689,7 @@ def update_value(self, 'metadata': new_metadata, 'type': new_type, 'synonyms': new_synonyms, - 'patterns': new_patterns + 'patterns': new_patterns, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2315,6 +2697,7 @@ def update_value(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2346,11 +2729,11 @@ def delete_value(self, workspace_id: str, entity: str, value: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2358,10 +2741,13 @@ def delete_value(self, workspace_id: str, entity: str, value: str, operation_id='delete_value') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2418,11 +2804,11 @@ def list_synonyms(self, :rtype: DetailedResponse with `dict` result representing a `SynonymCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2436,11 +2822,12 @@ def list_synonyms(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2486,11 +2873,11 @@ def create_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym must be provided') @@ -2500,15 +2887,21 @@ def create_synonym(self, operation_id='create_synonym') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'synonym': synonym} + data = { + 'synonym': synonym, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2549,13 +2942,13 @@ def get_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2563,10 +2956,14 @@ def get_synonym(self, operation_id='get_synonym') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2615,13 +3012,13 @@ def update_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2629,15 +3026,21 @@ def update_synonym(self, operation_id='update_synonym') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'synonym': new_synonym} + data = { + 'synonym': new_synonym, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2671,13 +3074,13 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2685,10 +3088,13 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, operation_id='delete_synonym') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2742,7 +3148,7 @@ def list_dialog_nodes(self, :rtype: DetailedResponse with `dict` result representing a `DialogNodeCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2756,11 +3162,12 @@ def list_dialog_nodes(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -2865,7 +3272,7 @@ def create_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node must be provided') @@ -2883,7 +3290,10 @@ def create_dialog_node(self, operation_id='create_dialog_node') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'dialog_node': dialog_node, @@ -2904,7 +3314,7 @@ def create_dialog_node(self, 'digress_out': digress_out, 'digress_out_slots': digress_out_slots, 'user_label': user_label, - 'disambiguation_opt_out': disambiguation_opt_out + 'disambiguation_opt_out': disambiguation_opt_out, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2912,6 +3322,7 @@ def create_dialog_node(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -2949,9 +3360,9 @@ def get_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2959,10 +3370,14 @@ def get_dialog_node(self, operation_id='get_dialog_node') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3072,9 +3487,9 @@ def update_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') if new_output is not None: new_output = convert_model(new_output) @@ -3090,7 +3505,10 @@ def update_dialog_node(self, operation_id='update_dialog_node') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'dialog_node': new_dialog_node, @@ -3111,7 +3529,7 @@ def update_dialog_node(self, 'digress_out': new_digress_out, 'digress_out_slots': new_digress_out_slots, 'user_label': new_user_label, - 'disambiguation_opt_out': new_disambiguation_opt_out + 'disambiguation_opt_out': new_disambiguation_opt_out, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3119,6 +3537,7 @@ def update_dialog_node(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3150,9 +3569,9 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3160,10 +3579,13 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, operation_id='delete_dialog_node') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3196,6 +3618,10 @@ def list_logs(self, List the events from the log of a specific workspace. This method requires Manager access. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). :param str workspace_id: Unique identifier of the workspace. :param str sort: (optional) How to sort the returned log events. You can @@ -3213,7 +3639,7 @@ def list_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3226,11 +3652,12 @@ def list_logs(self, 'sort': sort, 'filter': filter, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -3256,6 +3683,10 @@ def list_all_logs(self, List log events in all workspaces. List the events from the logs of all workspaces in the service instance. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). :param str filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that @@ -3277,7 +3708,7 @@ def list_all_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if filter is None: + if not filter: raise ValueError('filter must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3290,11 +3721,12 @@ def list_all_logs(self, 'filter': filter, 'sort': sort, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/logs' @@ -3333,7 +3765,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3341,10 +3773,14 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/user_data' @@ -3385,6 +3821,19 @@ class Sort(str, Enum): STABLE = 'stable' +class ExportWorkspaceAsyncEnums: + """ + Enums for export_workspace_async parameters. + """ + + class Sort(str, Enum): + """ + Indicates how the returned workspace data will be sorted. Specify `sort=stable` to + sort all workspace objects by unique identifier, in ascending alphabetical order. + """ + STABLE = 'stable' + + class ListIntentsEnums: """ Enums for list_intents parameters. @@ -3581,11 +4030,11 @@ def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] return cls(**args) @@ -3598,11 +4047,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list return _dict def _to_dict(self): @@ -3647,7 +4111,7 @@ def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': args = {} if 'output' in _dict: args['output'] = [ - BulkClassifyOutput.from_dict(x) for x in _dict.get('output') + BulkClassifyOutput.from_dict(v) for v in _dict.get('output') ] return cls(**args) @@ -3660,7 +4124,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x.to_dict() for x in self.output] + output_list = [] + for v in self.output: + if isinstance(v, dict): + output_list.append(v) + else: + output_list.append(v.to_dict()) + _dict['output'] = output_list return _dict def _to_dict(self): @@ -3850,7 +4320,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target.to_dict() + if isinstance(self.target, dict): + _dict['target'] = self.target + else: + _dict['target'] = self.target.to_dict() return _dict def _to_dict(self): @@ -3909,7 +4382,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'chat') and self.chat is not None: - _dict['chat'] = self.chat.to_dict() + if isinstance(self.chat, dict): + _dict['chat'] = self.chat + else: + _dict['chat'] = self.chat.to_dict() return _dict def _to_dict(self): @@ -3991,6 +4467,8 @@ class Context(): the previous response. :attr str conversation_id: (optional) The unique identifier of the conversation. + The conversation ID cannot contain any of the following characters: `+` `=` `&&` + `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` `~` `*` `?` `:` `\` `/`. :attr dict system: (optional) For internal use only. :attr MessageContextMetadata metadata: (optional) Metadata related to the message. @@ -4009,7 +4487,9 @@ def __init__(self, Initialize a Context object. :param str conversation_id: (optional) The unique identifier of the - conversation. + conversation. The conversation ID cannot contain any of the following + characters: `+` `=` `&&` `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` + `~` `*` `?` `:` `\` `/`. :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. @@ -4050,12 +4530,14 @@ def to_dict(self) -> Dict: if hasattr(self, 'system') and self.system is not None: _dict['system'] = self.system if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() + if isinstance(self.metadata, dict): + _dict['metadata'] = self.metadata + else: + _dict['metadata'] = self.metadata.to_dict() for _key in [ k for k in vars(self).keys() if k not in Context._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -4184,7 +4666,8 @@ class CounterexampleCollection(): :attr List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, counterexamples: List['Counterexample'], @@ -4195,6 +4678,7 @@ def __init__(self, counterexamples: List['Counterexample'], :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.counterexamples = counterexamples self.pagination = pagination @@ -4205,8 +4689,8 @@ def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': args = {} if 'counterexamples' in _dict: args['counterexamples'] = [ - Counterexample.from_dict(x) - for x in _dict.get('counterexamples') + Counterexample.from_dict(v) + for v in _dict.get('counterexamples') ] else: raise ValueError( @@ -4230,11 +4714,18 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'counterexamples') and self.counterexamples is not None: - _dict['counterexamples'] = [ - x.to_dict() for x in self.counterexamples - ] + counterexamples_list = [] + for v in self.counterexamples: + if isinstance(v, dict): + counterexamples_list.append(v) + else: + counterexamples_list.append(v.to_dict()) + _dict['counterexamples'] = counterexamples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -4333,7 +4824,7 @@ def from_dict(cls, _dict: Dict) -> 'CreateEntity': args['updated'] = string_to_datetime(_dict.get('updated')) if 'values' in _dict: args['values'] = [ - CreateValue.from_dict(x) for x in _dict.get('values') + CreateValue.from_dict(v) for v in _dict.get('values') ] return cls(**args) @@ -4358,7 +4849,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list return _dict def _to_dict(self): @@ -4441,7 +4938,7 @@ def from_dict(cls, _dict: Dict) -> 'CreateIntent': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') + Example.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -4462,7 +4959,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -4815,7 +5318,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNode': args['variable'] = _dict.get('variable') if 'actions' in _dict: args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') + DialogNodeAction.from_dict(v) for v in _dict.get('actions') ] if 'digress_in' in _dict: args['digress_in'] = _dict.get('digress_in') @@ -4855,13 +5358,22 @@ def to_dict(self) -> Dict: 'previous_sibling') and self.previous_sibling is not None: _dict['previous_sibling'] = self.previous_sibling if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'next_step') and self.next_step is not None: - _dict['next_step'] = self.next_step.to_dict() + if isinstance(self.next_step, dict): + _dict['next_step'] = self.next_step + else: + _dict['next_step'] = self.next_step.to_dict() if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'type') and self.type is not None: @@ -4871,7 +5383,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'variable') and self.variable is not None: _dict['variable'] = self.variable if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x.to_dict() for x in self.actions] + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'digress_in') and self.digress_in is not None: _dict['digress_in'] = self.digress_in if hasattr(self, 'digress_out') and self.digress_out is not None: @@ -5079,7 +5597,8 @@ class DialogNodeCollection(): :attr List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, dialog_nodes: List['DialogNode'], @@ -5090,6 +5609,7 @@ def __init__(self, dialog_nodes: List['DialogNode'], :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.dialog_nodes = dialog_nodes self.pagination = pagination @@ -5100,7 +5620,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': args = {} if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ - DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') ] else: raise ValueError( @@ -5123,9 +5643,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] + dialog_nodes_list = [] + for v in self.dialog_nodes: + if isinstance(v, dict): + dialog_nodes_list.append(v) + else: + dialog_nodes_list.append(v.to_dict()) + _dict['dialog_nodes'] = dialog_nodes_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -5194,8 +5723,7 @@ def to_dict(self) -> Dict: k for k in vars(self).keys() if k not in DialogNodeContext._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -5447,8 +5975,8 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': args = {} if 'generic' in _dict: args['generic'] = [ - DialogNodeOutputGeneric.from_dict(x) - for x in _dict.get('generic') + DialogNodeOutputGeneric.from_dict(v) + for v in _dict.get('generic') ] if 'integrations' in _dict: args['integrations'] = _dict.get('integrations') @@ -5468,17 +5996,25 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations if hasattr(self, 'modifiers') and self.modifiers is not None: - _dict['modifiers'] = self.modifiers.to_dict() + if isinstance(self.modifiers, dict): + _dict['modifiers'] = self.modifiers + else: + _dict['modifiers'] = self.modifiers.to_dict() for _key in [ k for k in vars(self).keys() if k not in DialogNodeOutput._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -5789,7 +6325,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -5859,11 +6398,11 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] return cls(**args) @@ -5876,11 +6415,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list return _dict def _to_dict(self): @@ -6045,6 +6599,9 @@ class DialogSuggestion(): :attr DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the next + message sent to the assistant. Do not modify or remove any of the included + properties. :attr dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. :attr str dialog_node: (optional) The unique ID of the dialog node that the @@ -6067,6 +6624,9 @@ def __init__(self, :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the + next message sent to the assistant. Do not modify or remove any of the + included properties. :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. :param str dialog_node: (optional) The unique ID of the dialog node that @@ -6111,7 +6671,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output if hasattr(self, 'dialog_node') and self.dialog_node is not None: @@ -6141,6 +6704,8 @@ class DialogSuggestionValue(): """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the next message + sent to the assistant. Do not modify or remove any of the included properties. :attr MessageInput input: (optional) An input object that includes the input text. @@ -6177,11 +6742,11 @@ def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] return cls(**args) @@ -6194,11 +6759,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list return _dict def _to_dict(self): @@ -6296,7 +6876,7 @@ def from_dict(cls, _dict: Dict) -> 'Entity': if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'values' in _dict: - args['values'] = [Value.from_dict(x) for x in _dict.get('values')] + args['values'] = [Value.from_dict(v) for v in _dict.get('values')] return cls(**args) @classmethod @@ -6320,7 +6900,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list return _dict def _to_dict(self): @@ -6348,7 +6934,8 @@ class EntityCollection(): :attr List[Entity] entities: An array of objects describing the entities defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, entities: List['Entity'], @@ -6359,6 +6946,7 @@ def __init__(self, entities: List['Entity'], :param List[Entity] entities: An array of objects describing the entities defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.entities = entities self.pagination = pagination @@ -6369,7 +6957,7 @@ def from_dict(cls, _dict: Dict) -> 'EntityCollection': args = {} if 'entities' in _dict: args['entities'] = [ - Entity.from_dict(x) for x in _dict.get('entities') + Entity.from_dict(v) for v in _dict.get('entities') ] else: raise ValueError( @@ -6392,9 +6980,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6503,7 +7100,8 @@ class EntityMentionCollection(): :attr List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, examples: List['EntityMention'], @@ -6514,6 +7112,7 @@ def __init__(self, examples: List['EntityMention'], :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.examples = examples self.pagination = pagination @@ -6524,7 +7123,7 @@ def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': args = {} if 'examples' in _dict: args['examples'] = [ - EntityMention.from_dict(x) for x in _dict.get('examples') + EntityMention.from_dict(v) for v in _dict.get('examples') ] else: raise ValueError( @@ -6547,9 +7146,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6617,7 +7225,7 @@ def from_dict(cls, _dict: Dict) -> 'Example': 'Required property \'text\' not present in Example JSON') if 'mentions' in _dict: args['mentions'] = [ - Mention.from_dict(x) for x in _dict.get('mentions') + Mention.from_dict(v) for v in _dict.get('mentions') ] if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) @@ -6636,7 +7244,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x.to_dict() for x in self.mentions] + mentions_list = [] + for v in self.mentions: + if isinstance(v, dict): + mentions_list.append(v) + else: + mentions_list.append(v.to_dict()) + _dict['mentions'] = mentions_list if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -6668,7 +7282,8 @@ class ExampleCollection(): :attr List[Example] examples: An array of objects describing the examples defined for the intent. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, examples: List['Example'], @@ -6679,6 +7294,7 @@ def __init__(self, examples: List['Example'], :param List[Example] examples: An array of objects describing the examples defined for the intent. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.examples = examples self.pagination = pagination @@ -6689,7 +7305,7 @@ def from_dict(cls, _dict: Dict) -> 'ExampleCollection': args = {} if 'examples' in _dict: args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') + Example.from_dict(v) for v in _dict.get('examples') ] else: raise ValueError( @@ -6712,9 +7328,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6797,7 +7422,7 @@ def from_dict(cls, _dict: Dict) -> 'Intent': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') + Example.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -6818,7 +7443,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -6846,7 +7477,8 @@ class IntentCollection(): :attr List[Intent] intents: An array of objects describing the intents defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, intents: List['Intent'], @@ -6857,6 +7489,7 @@ def __init__(self, intents: List['Intent'], :param List[Intent] intents: An array of objects describing the intents defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.intents = intents self.pagination = pagination @@ -6867,7 +7500,7 @@ def from_dict(cls, _dict: Dict) -> 'IntentCollection': args = {} if 'intents' in _dict: args['intents'] = [ - Intent.from_dict(x) for x in _dict.get('intents') + Intent.from_dict(v) for v in _dict.get('intents') ] else: raise ValueError( @@ -6890,9 +7523,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7011,9 +7653,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request.to_dict() + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response.to_dict() + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() if hasattr(self, 'log_id') and self.log_id is not None: _dict['log_id'] = self.log_id if hasattr(self, @@ -7054,6 +7702,7 @@ class LogCollection(): :attr List[Log] logs: An array of objects describing log events. :attr LogPagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: @@ -7062,7 +7711,8 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: :param List[Log] logs: An array of objects describing log events. :param LogPagination pagination: The pagination data for the returned - objects. + objects. For more information about using pagination, see + [Pagination](#pagination). """ self.logs = logs self.pagination = pagination @@ -7072,7 +7722,7 @@ def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} if 'logs' in _dict: - args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] + args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') @@ -7094,9 +7744,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'logs') and self.logs is not None: - _dict['logs'] = [x.to_dict() for x in self.logs] + logs_list = [] + for v in self.logs: + if isinstance(v, dict): + logs_list.append(v) + else: + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7189,7 +7848,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -7293,7 +7955,8 @@ class TypeEnum(str, Enum): class LogPagination(): """ - The pagination data for the returned objects. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). :attr str next_url: (optional) The URL that will return the next page of results, if any. @@ -7626,8 +8289,7 @@ def to_dict(self) -> Dict: k for k in vars(self).keys() if k not in MessageInput._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -7762,11 +8424,11 @@ def from_dict(cls, _dict: Dict) -> 'MessageRequest': args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') @@ -7776,7 +8438,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageRequest': args['output'] = OutputData.from_dict(_dict.get('output')) if 'actions' in _dict: args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') + DialogNodeAction.from_dict(v) for v in _dict.get('actions') ] if 'user_id' in _dict: args['user_id'] = _dict.get('user_id') @@ -7791,20 +8453,47 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: - _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + actions_list = [] + for v in getattr(self, 'actions'): + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -7914,7 +8603,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] else: raise ValueError( @@ -7922,7 +8611,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] else: raise ValueError( @@ -7944,7 +8633,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'actions' in _dict: args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') + DialogNodeAction.from_dict(v) for v in _dict.get('actions') ] if 'user_id' in _dict: args['user_id'] = _dict.get('user_id') @@ -7963,20 +8652,47 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: - _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + actions_list = [] + for v in getattr(self, 'actions'): + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -8064,12 +8780,12 @@ def from_dict(cls, _dict: Dict) -> 'OutputData': args['nodes_visited'] = _dict.get('nodes_visited') if 'nodes_visited_details' in _dict: args['nodes_visited_details'] = [ - DialogNodeVisitedDetails.from_dict(x) - for x in _dict.get('nodes_visited_details') + DialogNodeVisitedDetails.from_dict(v) + for v in _dict.get('nodes_visited_details') ] if 'log_messages' in _dict: args['log_messages'] = [ - LogMessage.from_dict(x) for x in _dict.get('log_messages') + LogMessage.from_dict(v) for v in _dict.get('log_messages') ] else: raise ValueError( @@ -8077,8 +8793,8 @@ def from_dict(cls, _dict: Dict) -> 'OutputData': ) if 'generic' in _dict: args['generic'] = [ - RuntimeResponseGeneric.from_dict(x) - for x in _dict.get('generic') + RuntimeResponseGeneric.from_dict(v) + for v in _dict.get('generic') ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -8096,18 +8812,33 @@ def to_dict(self) -> Dict: _dict['nodes_visited'] = self.nodes_visited if hasattr(self, 'nodes_visited_details' ) and self.nodes_visited_details is not None: - _dict['nodes_visited_details'] = [ - x.to_dict() for x in self.nodes_visited_details - ] + nodes_visited_details_list = [] + for v in self.nodes_visited_details: + if isinstance(v, dict): + nodes_visited_details_list.append(v) + else: + nodes_visited_details_list.append(v.to_dict()) + _dict['nodes_visited_details'] = nodes_visited_details_list if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x.to_dict() for x in self.log_messages] + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list for _key in [ k for k in vars(self).keys() if k not in OutputData._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -8152,7 +8883,8 @@ def __ne__(self, other: 'OutputData') -> bool: class Pagination(): """ - The pagination data for the returned objects. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). :attr str refresh_url: The URL that will return the same page of results. :attr str next_url: (optional) The URL that will return the next page of @@ -8264,6 +8996,7 @@ class ResponseGenericChannel(): ResponseGenericChannel. :attr str channel: (optional) A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ def __init__(self, *, channel: str = None) -> None: @@ -8272,6 +9005,7 @@ def __init__(self, *, channel: str = None) -> None: :param str channel: (optional) A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ self.channel = channel @@ -8316,6 +9050,7 @@ def __ne__(self, other: 'ResponseGenericChannel') -> bool: class ChannelEnum(str, Enum): """ A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ CHAT = 'chat' FACEBOOK = 'facebook' @@ -8423,15 +9158,15 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args['confidence'] = _dict.get('confidence') if 'groups' in _dict: args['groups'] = [ - CaptureGroup.from_dict(x) for x in _dict.get('groups') + CaptureGroup.from_dict(v) for v in _dict.get('groups') ] if 'interpretation' in _dict: args['interpretation'] = RuntimeEntityInterpretation.from_dict( _dict.get('interpretation')) if 'alternatives' in _dict: args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(x) - for x in _dict.get('alternatives') + RuntimeEntityAlternative.from_dict(v) + for v in _dict.get('alternatives') ] if 'role' in _dict: args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) @@ -8454,13 +9189,31 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x.to_dict() for x in self.groups] + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role.to_dict() + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() return _dict def _to_dict(self): @@ -8988,17 +9741,20 @@ class RuntimeIntent(): An intent identified in the user input. :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. """ - def __init__(self, intent: str, confidence: float) -> None: + def __init__(self, intent: str, *, confidence: float = None) -> None: """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's - confidence in the intent. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the intent. If you are specifying an intent as part + of a request, but you do not have a calculated confidence value, specify + `1`. """ self.intent = intent self.confidence = confidence @@ -9015,10 +9771,6 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in RuntimeIntent JSON' - ) return cls(**args) @classmethod @@ -9143,6 +9895,61 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) +class StatusError(): + """ + An object describing an error that occurred during processing of an asynchronous + operation. + + :attr str message: (optional) The text of the error message. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a StatusError object. + + :param str message: (optional) The text of the error message. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatusError object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatusError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatusError') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatusError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Synonym(): """ Synonym. @@ -9228,7 +10035,8 @@ class SynonymCollection(): SynonymCollection. :attr List[Synonym] synonyms: An array of synonyms. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, synonyms: List['Synonym'], @@ -9238,6 +10046,7 @@ def __init__(self, synonyms: List['Synonym'], :param List[Synonym] synonyms: An array of synonyms. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.synonyms = synonyms self.pagination = pagination @@ -9248,7 +10057,7 @@ def from_dict(cls, _dict: Dict) -> 'SynonymCollection': args = {} if 'synonyms' in _dict: args['synonyms'] = [ - Synonym.from_dict(x) for x in _dict.get('synonyms') + Synonym.from_dict(v) for v in _dict.get('synonyms') ] else: raise ValueError( @@ -9271,9 +10080,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'synonyms') and self.synonyms is not None: - _dict['synonyms'] = [x.to_dict() for x in self.synonyms] + synonyms_list = [] + for v in self.synonyms: + if isinstance(v, dict): + synonyms_list.append(v) + else: + synonyms_list.append(v.to_dict()) + _dict['synonyms'] = synonyms_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9439,7 +10257,8 @@ class ValueCollection(): ValueCollection. :attr List[Value] values: An array of entity values. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: @@ -9448,6 +10267,7 @@ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: :param List[Value] values: An array of entity values. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.values = values self.pagination = pagination @@ -9457,7 +10277,7 @@ def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} if 'values' in _dict: - args['values'] = [Value.from_dict(x) for x in _dict.get('values')] + args['values'] = [Value.from_dict(v) for v in _dict.get('values')] else: raise ValueError( 'Required property \'values\' not present in ValueCollection JSON' @@ -9479,9 +10299,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9552,7 +10381,7 @@ def from_dict(cls, _dict: Dict) -> 'Webhook': 'Required property \'name\' not present in Webhook JSON') if 'headers' in _dict: args['headers_'] = [ - WebhookHeader.from_dict(x) for x in _dict.get('headers') + WebhookHeader.from_dict(v) for v in _dict.get('headers') ] return cls(**args) @@ -9569,7 +10398,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'headers_') and self.headers_ is not None: - _dict['headers'] = [x.to_dict() for x in self.headers_] + headers_list = [] + for v in self.headers_: + if isinstance(v, dict): + headers_list.append(v) + else: + headers_list.append(v.to_dict()) + _dict['headers'] = headers_list return _dict def _to_dict(self): @@ -9681,11 +10516,25 @@ class Workspace(): improvements. `true` indicates that workspace training data is not to be used. :attr WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :attr str status: (optional) The current status of the workspace. + :attr str status: (optional) The current status of the workspace: + - **Available**: The workspace is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The workspace does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The workspace is training based on new data such as intents or + examples. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. :attr List[Webhook] webhooks: (optional) :attr List[Intent] intents: (optional) An array of intents. :attr List[Entity] entities: (optional) An array of objects describing the entities for the workspace. + :attr WorkspaceCounts counts: (optional) An object containing properties that + indicate how many intents, entities, and dialog nodes are defined in the + workspace. This property is included only in responses from the **Export + workspace asynchronously** method, and only when the **verbose** query parameter + is set to `true`. """ def __init__(self, @@ -9702,9 +10551,11 @@ def __init__(self, metadata: dict = None, system_settings: 'WorkspaceSystemSettings' = None, status: str = None, + status_errors: List['StatusError'] = None, webhooks: List['Webhook'] = None, intents: List['Intent'] = None, - entities: List['Entity'] = None) -> None: + entities: List['Entity'] = None, + counts: 'WorkspaceCounts' = None) -> None: """ Initialize a Workspace object. @@ -9741,9 +10592,11 @@ def __init__(self, self.learning_opt_out = learning_opt_out self.system_settings = system_settings self.status = status + self.status_errors = status_errors self.webhooks = webhooks self.intents = intents self.entities = entities + self.counts = counts @classmethod def from_dict(cls, _dict: Dict) -> 'Workspace': @@ -9765,12 +10618,12 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': args['workspace_id'] = _dict.get('workspace_id') if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ - DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') ] if 'counterexamples' in _dict: args['counterexamples'] = [ - Counterexample.from_dict(x) - for x in _dict.get('counterexamples') + Counterexample.from_dict(v) + for v in _dict.get('counterexamples') ] if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) @@ -9789,18 +10642,24 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': _dict.get('system_settings')) if 'status' in _dict: args['status'] = _dict.get('status') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(v) for v in _dict.get('status_errors') + ] if 'webhooks' in _dict: args['webhooks'] = [ - Webhook.from_dict(x) for x in _dict.get('webhooks') + Webhook.from_dict(v) for v in _dict.get('webhooks') ] if 'intents' in _dict: args['intents'] = [ - Intent.from_dict(x) for x in _dict.get('intents') + Intent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - Entity.from_dict(x) for x in _dict.get('entities') + Entity.from_dict(v) for v in _dict.get('entities') ] + if 'counts' in _dict: + args['counts'] = WorkspaceCounts.from_dict(_dict.get('counts')) return cls(**args) @classmethod @@ -9821,12 +10680,22 @@ def to_dict(self) -> Dict: self, 'workspace_id') is not None: _dict['workspace_id'] = getattr(self, 'workspace_id') if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] + dialog_nodes_list = [] + for v in self.dialog_nodes: + if isinstance(v, dict): + dialog_nodes_list.append(v) + else: + dialog_nodes_list.append(v.to_dict()) + _dict['dialog_nodes'] = dialog_nodes_list if hasattr(self, 'counterexamples') and self.counterexamples is not None: - _dict['counterexamples'] = [ - x.to_dict() for x in self.counterexamples - ] + counterexamples_list = [] + for v in self.counterexamples: + if isinstance(v, dict): + counterexamples_list.append(v) + else: + counterexamples_list.append(v.to_dict()) + _dict['counterexamples'] = counterexamples_list if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -9838,15 +10707,50 @@ def to_dict(self) -> Dict: _dict['learning_opt_out'] = self.learning_opt_out if hasattr(self, 'system_settings') and self.system_settings is not None: - _dict['system_settings'] = self.system_settings.to_dict() + if isinstance(self.system_settings, dict): + _dict['system_settings'] = self.system_settings + else: + _dict['system_settings'] = self.system_settings.to_dict() if hasattr(self, 'status') and getattr(self, 'status') is not None: _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list if hasattr(self, 'webhooks') and self.webhooks is not None: - _dict['webhooks'] = [x.to_dict() for x in self.webhooks] + webhooks_list = [] + for v in self.webhooks: + if isinstance(v, dict): + webhooks_list.append(v) + else: + webhooks_list.append(v.to_dict()) + _dict['webhooks'] = webhooks_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'counts') and getattr(self, 'counts') is not None: + if isinstance(getattr(self, 'counts'), dict): + _dict['counts'] = getattr(self, 'counts') + else: + _dict['counts'] = getattr(self, 'counts').to_dict() return _dict def _to_dict(self): @@ -9869,12 +10773,20 @@ def __ne__(self, other: 'Workspace') -> bool: class StatusEnum(str, Enum): """ - The current status of the workspace. + The current status of the workspace: + - **Available**: The workspace is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The workspace does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The workspace is training based on new data such as intents or + examples. """ + AVAILABLE = 'Available' + FAILED = 'Failed' NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' TRAINING = 'Training' - FAILED = 'Failed' - AVAILABLE = 'Available' UNAVAILABLE = 'Unavailable' @@ -9884,7 +10796,8 @@ class WorkspaceCollection(): :attr List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, workspaces: List['Workspace'], @@ -9895,6 +10808,7 @@ def __init__(self, workspaces: List['Workspace'], :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.workspaces = workspaces self.pagination = pagination @@ -9905,7 +10819,7 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': args = {} if 'workspaces' in _dict: args['workspaces'] = [ - Workspace.from_dict(x) for x in _dict.get('workspaces') + Workspace.from_dict(v) for v in _dict.get('workspaces') ] else: raise ValueError( @@ -9928,9 +10842,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'workspaces') and self.workspaces is not None: - _dict['workspaces'] = [x.to_dict() for x in self.workspaces] + workspaces_list = [] + for v in self.workspaces: + if isinstance(v, dict): + workspaces_list.append(v) + else: + workspaces_list.append(v.to_dict()) + _dict['workspaces'] = workspaces_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9952,6 +10875,83 @@ def __ne__(self, other: 'WorkspaceCollection') -> bool: return not self == other +class WorkspaceCounts(): + """ + An object containing properties that indicate how many intents, entities, and dialog + nodes are defined in the workspace. This property is included only in responses from + the **Export workspace asynchronously** method, and only when the **verbose** query + parameter is set to `true`. + + :attr int intent: (optional) The number of intents defined in the workspace. + :attr int entity: (optional) The number of entities defined in the workspace. + :attr int node: (optional) The number of nodes defined in the workspace. + """ + + def __init__(self, + *, + intent: int = None, + entity: int = None, + node: int = None) -> None: + """ + Initialize a WorkspaceCounts object. + + :param int intent: (optional) The number of intents defined in the + workspace. + :param int entity: (optional) The number of entities defined in the + workspace. + :param int node: (optional) The number of nodes defined in the workspace. + """ + self.intent = intent + self.entity = entity + self.node = node + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceCounts': + """Initialize a WorkspaceCounts object from a json dictionary.""" + args = {} + if 'intent' in _dict: + args['intent'] = _dict.get('intent') + if 'entity' in _dict: + args['entity'] = _dict.get('entity') + if 'node' in _dict: + args['node'] = _dict.get('node') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceCounts object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'node') and self.node is not None: + _dict['node'] = self.node + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this WorkspaceCounts object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceCounts') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'WorkspaceCounts') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class WorkspaceSystemSettings(): """ Global settings for the workspace. @@ -9973,13 +10973,15 @@ class WorkspaceSystemSettings(): Workspace settings related to the behavior of system entities. :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. + :attr WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to + the version of the training algorithms currently used by the skill. """ # The set of defined properties for the class _properties = frozenset([ 'tooling', 'disambiguation', 'human_agent_assist', 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', - 'off_topic' + 'off_topic', 'nlp' ]) def __init__( @@ -9992,6 +10994,7 @@ def __init__( spelling_auto_correct: bool = None, system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, off_topic: 'WorkspaceSystemSettingsOffTopic' = None, + nlp: 'WorkspaceSystemSettingsNlp' = None, **kwargs) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -10014,6 +11017,9 @@ def __init__( Workspace settings related to the behavior of system entities. :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. + :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings + related to the version of the training algorithms currently used by the + skill. :param **kwargs: (optional) Any additional properties. """ self.tooling = tooling @@ -10023,6 +11029,7 @@ def __init__( self.spelling_auto_correct = spelling_auto_correct self.system_entities = system_entities self.off_topic = off_topic + self.nlp = nlp for _key, _value in kwargs.items(): setattr(self, _key, _value) @@ -10050,6 +11057,8 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': if 'off_topic' in _dict: args['off_topic'] = WorkspaceSystemSettingsOffTopic.from_dict( _dict.get('off_topic')) + if 'nlp' in _dict: + args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(_dict.get('nlp')) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -10063,9 +11072,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tooling') and self.tooling is not None: - _dict['tooling'] = self.tooling.to_dict() + if isinstance(self.tooling, dict): + _dict['tooling'] = self.tooling + else: + _dict['tooling'] = self.tooling.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation.to_dict() + if isinstance(self.disambiguation, dict): + _dict['disambiguation'] = self.disambiguation + else: + _dict['disambiguation'] = self.disambiguation.to_dict() if hasattr( self, 'human_agent_assist') and self.human_agent_assist is not None: @@ -10078,15 +11093,25 @@ def to_dict(self) -> Dict: _dict['spelling_auto_correct'] = self.spelling_auto_correct if hasattr(self, 'system_entities') and self.system_entities is not None: - _dict['system_entities'] = self.system_entities.to_dict() + if isinstance(self.system_entities, dict): + _dict['system_entities'] = self.system_entities + else: + _dict['system_entities'] = self.system_entities.to_dict() if hasattr(self, 'off_topic') and self.off_topic is not None: - _dict['off_topic'] = self.off_topic.to_dict() + if isinstance(self.off_topic, dict): + _dict['off_topic'] = self.off_topic + else: + _dict['off_topic'] = self.off_topic.to_dict() + if hasattr(self, 'nlp') and self.nlp is not None: + if isinstance(self.nlp, dict): + _dict['nlp'] = self.nlp + else: + _dict['nlp'] = self.nlp.to_dict() for _key in [ k for k in vars(self).keys() if k not in WorkspaceSystemSettings._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -10270,6 +11295,71 @@ class SensitivityEnum(str, Enum): LOW = 'low' +class WorkspaceSystemSettingsNlp(): + """ + Workspace settings related to the version of the training algorithms currently used by + the skill. + + :attr str model: (optional) The policy the skill follows for selecting the + algorithm version to use. For more information, see the + [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). + On IBM Cloud, you can specify `latest`, `previous`, or `beta`. + On IBM Cloud Pak for Data, you can specify either `beta` or the date of the + version you want to use, in `YYYY-MM-DD` format. + """ + + def __init__(self, *, model: str = None) -> None: + """ + Initialize a WorkspaceSystemSettingsNlp object. + + :param str model: (optional) The policy the skill follows for selecting the + algorithm version to use. For more information, see the + [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). + On IBM Cloud, you can specify `latest`, `previous`, or `beta`. + On IBM Cloud Pak for Data, you can specify either `beta` or the date of + the version you want to use, in `YYYY-MM-DD` format. + """ + self.model = model + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsNlp': + """Initialize a WorkspaceSystemSettingsNlp object from a json dictionary.""" + args = {} + if 'model' in _dict: + args['model'] = _dict.get('model') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsNlp object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this WorkspaceSystemSettingsNlp object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceSystemSettingsNlp') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'WorkspaceSystemSettingsNlp') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class WorkspaceSystemSettingsOffTopic(): """ Workspace settings related to detection of irrelevant input. @@ -10455,7 +11545,7 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio( specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -10467,7 +11557,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object. @@ -10483,7 +11573,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -10520,8 +11610,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -10546,7 +11636,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -10584,6 +11680,8 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer( :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. :attr str message_to_user: The message to display to the user when initiating a channel transfer. :attr ChannelTransferInfo transfer_info: Information used by an integration to @@ -10604,6 +11702,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an @@ -10644,8 +11744,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -10663,9 +11763,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -10778,8 +11887,8 @@ def from_dict( _dict.get('transfer_info')) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -10798,14 +11907,29 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -10911,8 +12035,8 @@ def from_dict( args['image_url'] = _dict.get('image_url') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -10935,7 +12059,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11033,8 +12163,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'alt_text' in _dict: args['alt_text'] = _dict.get('alt_text') @@ -11057,7 +12187,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -11161,8 +12297,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) + for v in _dict.get('options') ] else: raise ValueError( @@ -11170,8 +12306,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11192,9 +12328,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11289,8 +12437,8 @@ def from_dict( args['typing'] = _dict.get('typing') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11309,7 +12457,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11428,8 +12582,8 @@ def from_dict( args['discovery_version'] = _dict.get('discovery_version') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11453,7 +12607,13 @@ def to_dict(self) -> Dict: 'discovery_version') and self.discovery_version is not None: _dict['discovery_version'] = self.discovery_version if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11548,8 +12708,8 @@ def from_dict( ) if 'values' in _dict: args['values'] = [ - DialogNodeOutputTextValuesElement.from_dict(x) - for x in _dict.get('values') + DialogNodeOutputTextValuesElement.from_dict(v) + for v in _dict.get('values') ] else: raise ValueError( @@ -11561,8 +12721,8 @@ def from_dict( args['delimiter'] = _dict.get('delimiter') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11577,14 +12737,26 @@ def to_dict(self) -> Dict: if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list if hasattr(self, 'selection_policy') and self.selection_policy is not None: _dict['selection_policy'] = self.selection_policy if hasattr(self, 'delimiter') and self.delimiter is not None: _dict['delimiter'] = self.delimiter if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11674,8 +12846,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11692,7 +12864,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11735,7 +12913,7 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo( specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -11747,7 +12925,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object. @@ -11763,7 +12941,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -11800,8 +12978,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -11826,7 +13004,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -11871,7 +13055,7 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -11883,7 +13067,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -11900,7 +13084,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -11937,8 +13121,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -11963,7 +13147,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -11999,6 +13189,8 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. :attr str message_to_user: The message to display to the user when initiating a channel transfer. :attr ChannelTransferInfo transfer_info: Information used by an integration to @@ -12021,6 +13213,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an @@ -12063,8 +13257,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12082,9 +13276,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12219,8 +13422,8 @@ def from_dict( args['dialog_node'] = _dict.get('dialog_node') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12239,18 +13442,33 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12354,8 +13572,8 @@ def from_dict( args['image_url'] = _dict.get('image_url') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12378,7 +13596,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12480,8 +13704,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'alt_text' in _dict: args['alt_text'] = _dict.get('alt_text') @@ -12504,7 +13728,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -12605,8 +13835,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) + for v in _dict.get('options') ] else: raise ValueError( @@ -12614,8 +13844,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12636,9 +13866,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12734,8 +13976,8 @@ def from_dict( args['typing'] = _dict.get('typing') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12754,7 +13996,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12841,7 +14089,7 @@ def from_dict( ) if 'suggestions' in _dict: args['suggestions'] = [ - DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') ] else: raise ValueError( @@ -12849,8 +14097,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12867,9 +14115,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + suggestions_list = [] + for v in self.suggestions: + if isinstance(v, dict): + suggestions_list.append(v) + else: + suggestions_list.append(v.to_dict()) + _dict['suggestions'] = suggestions_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12950,8 +14210,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12968,7 +14228,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13050,8 +14316,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -13068,7 +14334,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13108,7 +14380,7 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -13120,7 +14392,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -13137,7 +14409,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -13174,8 +14446,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -13200,7 +14472,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index b9413e510..1875780d3 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -26,6 +26,7 @@ See: https://cloud.ibm.com/docs/assistant """ +from datetime import datetime from enum import Enum from typing import Dict, List import json @@ -34,7 +35,7 @@ from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_model +from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime from .common import get_sdk_headers @@ -76,11 +77,189 @@ def __init__( self.version = version self.configure_service(service_name) + ######################### + # Assistants + ######################### + + def create_assistant(self, + *, + language: str = None, + name: str = None, + description: str = None, + **kwargs) -> DetailedResponse: + """ + Create an assistant. + + Create a new assistant. + This method is available only with Enterprise plans. + + :param str language: (optional) The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AssistantData` object + """ + + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_assistant') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'language': language, + 'name': name, + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/assistants' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def list_assistants(self, + *, + page_limit: int = None, + include_count: bool = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + List assistants. + + List the assistants associated with a Watson Assistant service instance. + This method is available only with Enterprise plans. + + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned assistants will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AssistantCollection` object + """ + + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_assistants') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/assistants' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: + """ + Delete assistant. + + Delete an assistant. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_assistant') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}'.format(**path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + ######################### # Sessions ######################### - def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: + def create_session(self, + assistant_id: str, + *, + analytics: 'RequestAnalytics' = None, + **kwargs) -> DetailedResponse: """ Create a session. @@ -90,29 +269,50 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings). - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SessionResponse` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') + if analytics is not None: + analytics = convert_model(analytics) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='create_session') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } + + data = { + 'analytics': analytics, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id'] @@ -122,7 +322,8 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response @@ -136,21 +337,27 @@ def delete_session(self, assistant_id: str, session_id: str, session inactivity timeout, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings)). - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str session_id: Unique identifier of the session. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if session_id is None: + if not session_id: raise ValueError('session_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -158,10 +365,13 @@ def delete_session(self, assistant_id: str, session_id: str, operation_id='delete_session') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id', 'session_id'] @@ -196,12 +406,18 @@ def message(self, (including context data) stored by Watson Assistant for the duration of the session. - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str session_id: Unique identifier of the session. :param MessageInput input: (optional) An input object that includes the input text. @@ -226,9 +442,9 @@ def message(self, :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if session_id is None: + if not session_id: raise ValueError('session_id must be provided') if input is not None: input = convert_model(input) @@ -240,15 +456,22 @@ def message(self, operation_id='message') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input, 'context': context, 'user_id': user_id} + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id', 'session_id'] @@ -278,12 +501,18 @@ def message_stateless(self, Send user input to an assistant and receive a response, with conversation state (including context data) managed by your application. - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param MessageInputStateless input: (optional) An input object that includes the input text. :param MessageContextStateless context: (optional) Context data for the @@ -308,7 +537,7 @@ def message_stateless(self, :rtype: DetailedResponse with `dict` result representing a `MessageResponseStateless` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') if input is not None: input = convert_model(input) @@ -320,15 +549,22 @@ def message_stateless(self, operation_id='message_stateless') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input, 'context': context, 'user_id': user_id} + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id'] @@ -348,10 +584,7 @@ def message_stateless(self, # Bulk classify ######################### - def bulk_classify(self, - skill_id: str, - *, - input: List['BulkClassifyUtterance'] = None, + def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], **kwargs) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -365,32 +598,38 @@ def bulk_classify(self, :param str skill_id: Unique identifier of the skill. To find the skill ID in the Watson Assistant user interface, open the skill settings and click **API Details**. - :param List[BulkClassifyUtterance] input: (optional) An array of input - utterances to classify. + :param List[BulkClassifyUtterance] input: An array of input utterances to + classify. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object """ - if skill_id is None: + if not skill_id: raise ValueError('skill_id must be provided') - if input is not None: - input = [convert_model(x) for x in input] + if input is None: + raise ValueError('input must be provided') + input = [convert_model(x) for x in input] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='bulk_classify') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input} + data = { + 'input': input, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['skill_id'] @@ -423,14 +662,25 @@ def list_logs(self, List log events for an assistant. List the events from the log of an assistant. - This method requires Manager access, and is available only with Enterprise plans. - - :param str assistant_id: Unique identifier of the assistant. To find the - assistant ID in the Watson Assistant user interface, open the assistant - settings and click **API Details**. For information about creating - assistants, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + This method requires Manager access, and is available only with Plus and + Enterprise plans. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str sort: (optional) How to sort the returned log events. You can sort by **request_timestamp**. To reverse the sort order, prefix the parameter value with a minus sign (`-`). @@ -446,7 +696,7 @@ def list_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -459,11 +709,12 @@ def list_logs(self, 'sort': sort, 'filter': filter, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id'] @@ -505,7 +756,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -513,10 +764,14 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v2/user_data' @@ -528,434 +783,1067 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response + ######################### + # Environments + ######################### -############################################################################## -# Models -############################################################################## + def list_environments(self, + assistant_id: str, + *, + page_limit: int = None, + include_count: bool = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + List environments. + + List the environments associated with an assistant. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned environments + will be sorted. To reverse the sort order, prefix the value with a minus + sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `EnvironmentCollection` object + """ + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_environments') + headers.update(sdk_headers) -class AgentAvailabilityMessage(): - """ - AgentAvailabilityMessage. + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } - :attr str message: (optional) The text of the message. - """ + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def __init__(self, *, message: str = None) -> None: - """ - Initialize a AgentAvailabilityMessage object. + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - :param str message: (optional) The text of the message. + response = self.send(request, **kwargs) + return response + + def get_environment(self, + assistant_id: str, + environment_id: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Get environment. + + Get information about an environment. For more information about environments, see + [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the Watson Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - self.message = message - @classmethod - def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') - return cls(**args) + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_environment') + headers.update(sdk_headers) - @classmethod - def _from_dict(cls, _dict): - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - return cls.from_dict(_dict) + params = { + 'version': self.version, + 'include_audit': include_audit, + } - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - return _dict + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - def __str__(self) -> str: - """Return a `str` version of this AgentAvailabilityMessage object.""" - return json.dumps(self.to_dict(), indent=2) + response = self.send(request, **kwargs) + return response - def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + def update_environment(self, + assistant_id: str, + environment_id: str, + *, + name: str = None, + description: str = None, + session_timeout: int = None, + skill_references: List['EnvironmentSkill'] = None, + **kwargs) -> DetailedResponse: + """ + Update environment. + + Update an environment with new or modified data. For more information about + environments, see + [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the Watson Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + :param int session_timeout: (optional) The session inactivity timeout + setting for the environment (in seconds). + :param List[EnvironmentSkill] skill_references: (optional) An array of + objects identifying the skills (such as action and dialog) that exist in + the environment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Environment` object + """ - def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if skill_references is not None: + skill_references = [convert_model(x) for x in skill_references] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_environment') + headers.update(sdk_headers) + params = { + 'version': self.version, + } -class BulkClassifyOutput(): - """ - BulkClassifyOutput. + data = { + 'name': name, + 'description': description, + 'session_timeout': session_timeout, + 'skill_references': skill_references, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - :attr BulkClassifyUtterance input: (optional) The user input utterance to - classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the utterance. - """ - - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: - """ - Initialize a BulkClassifyOutput object. - - :param BulkClassifyUtterance input: (optional) The user input utterance to - classify. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the utterance. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the utterance. - """ - self.input = input - self.entities = entities - self.intents = intents + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': - """Initialize a BulkClassifyOutput object from a json dictionary.""" - args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - return cls(**args) + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) - @classmethod - def _from_dict(cls, _dict): - """Initialize a BulkClassifyOutput object from a json dictionary.""" - return cls.from_dict(_dict) + response = self.send(request, **kwargs) + return response - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - return _dict + ######################### + # Releases + ######################### - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + def create_release(self, + assistant_id: str, + *, + description: str = None, + **kwargs) -> DetailedResponse: + """ + Create release. + + Create a new release using the current content of the dialog and action skills in + the draft environment. (In the Watson Assistant user interface, a release is + called a *version*.) + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str description: (optional) The description of the release. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Release` object + """ - def __str__(self) -> str: - """Return a `str` version of this BulkClassifyOutput object.""" - return json.dumps(self.to_dict(), indent=2) + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_release') + headers.update(sdk_headers) - def __eq__(self, other: 'BulkClassifyOutput') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + params = { + 'version': self.version, + } - def __ne__(self, other: 'BulkClassifyOutput') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + data = { + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class BulkClassifyResponse(): - """ - BulkClassifyResponse. + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) - :attr List[BulkClassifyOutput] output: (optional) An array of objects that - contain classification information for the submitted input utterances. - """ + response = self.send(request, **kwargs) + return response - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + def list_releases(self, + assistant_id: str, + *, + page_limit: int = None, + include_count: bool = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> DetailedResponse: """ - Initialize a BulkClassifyResponse object. - - :param List[BulkClassifyOutput] output: (optional) An array of objects that - contain classification information for the submitted input utterances. + List releases. + + List the releases associated with an assistant. (In the Watson Assistant user + interface, a release is called a *version*.) + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned workspaces will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ReleaseCollection` object """ - self.output = output - @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': - """Initialize a BulkClassifyResponse object from a json dictionary.""" - args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(x) for x in _dict.get('output') - ] - return cls(**args) + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_releases') + headers.update(sdk_headers) - @classmethod - def _from_dict(cls, _dict): - """Initialize a BulkClassifyResponse object from a json dictionary.""" - return cls.from_dict(_dict) + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x.to_dict() for x in self.output] - return _dict + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - def __str__(self) -> str: - """Return a `str` version of this BulkClassifyResponse object.""" - return json.dumps(self.to_dict(), indent=2) + response = self.send(request, **kwargs) + return response - def __eq__(self, other: 'BulkClassifyResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + def get_release(self, + assistant_id: str, + release: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Get release. + + Get information about a release. + Release data is not available until publishing of the release completes. If + publishing is still in progress, you can continue to poll by calling the same + request again and checking the value of the **status** property. When processing + has completed, the request returns the release data. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str release: Unique identifier of the release. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Release` object + """ - def __ne__(self, other: 'BulkClassifyResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_release') + headers.update(sdk_headers) + params = { + 'version': self.version, + 'include_audit': include_audit, + } -class BulkClassifyUtterance(): - """ - The user input utterance to classify. + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - :attr str text: The text of the input utterance. - """ + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - def __init__(self, text: str) -> None: - """ - Initialize a BulkClassifyUtterance object. + response = self.send(request, **kwargs) + return response - :param str text: The text of the input utterance. + def delete_release(self, assistant_id: str, release: str, + **kwargs) -> DetailedResponse: + """ + Delete release. + + Delete a release. (In the Watson Assistant user interface, a release is called a + *version*.) + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str release: Unique identifier of the release. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': - """Initialize a BulkClassifyUtterance object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in BulkClassifyUtterance JSON' - ) - return cls(**args) - @classmethod - def _from_dict(cls, _dict): - """Initialize a BulkClassifyUtterance object from a json dictionary.""" - return cls.from_dict(_dict) + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_release') + headers.update(sdk_headers) - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - return _dict + params = { + 'version': self.version, + } - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def __str__(self) -> str: - """Return a `str` version of this BulkClassifyUtterance object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'BulkClassifyUtterance') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'BulkClassifyUtterance') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + response = self.send(request, **kwargs) + return response -class CaptureGroup(): - """ - CaptureGroup. + def deploy_release(self, + assistant_id: str, + release: str, + environment_id: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Deploy release. + + Update the environment with the content of the release. All snapshots saved as + part of the release become active in the environment. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str release: Unique identifier of the release. + :param str environment_id: The environment ID of the environment where the + release is to be deployed. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Environment` object + """ - :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. - """ + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + if environment_id is None: + raise ValueError('environment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='deploy_release') + headers.update(sdk_headers) - def __init__(self, group: str, *, location: List[int] = None) -> None: - """ - Initialize a CaptureGroup object. + params = { + 'version': self.version, + 'include_audit': include_audit, + } - :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 + data = { + 'environment_id': environment_id, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - @classmethod - def from_dict(cls, _dict: Dict) -> 'CaptureGroup': - """Initialize a CaptureGroup object from a json dictionary.""" - args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') - else: - raise ValueError( - 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') - return cls(**args) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - @classmethod - def _from_dict(cls, _dict): - """Initialize a CaptureGroup object from a json dictionary.""" - return cls.from_dict(_dict) + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}/deploy'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'group') and self.group is not None: - _dict['group'] = self.group - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - return _dict + response = self.send(request, **kwargs) + return response - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + ######################### + # Skills + ######################### - def __str__(self) -> str: - """Return a `str` version of this CaptureGroup object.""" - return json.dumps(self.to_dict(), indent=2) + def get_skill(self, assistant_id: str, skill_id: str, + **kwargs) -> DetailedResponse: + """ + Get skill. + + Get information about a skill. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the Watson Assistant user interface, open the skill settings and click + **API Details**. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object + """ - def __eq__(self, other: 'CaptureGroup') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_skill') + headers.update(sdk_headers) - def __ne__(self, other: 'CaptureGroup') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + params = { + 'version': self.version, + } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class ChannelTransferInfo(): - """ - Information used by an integration to transfer the conversation to a different - channel. + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - :attr ChannelTransferTarget target: An object specifying target channels - available for the transfer. Each property of this object represents an available - transfer target. Currently, the only supported property is **chat**, - representing the web chat integration. - """ + response = self.send(request, **kwargs) + return response - def __init__(self, target: 'ChannelTransferTarget') -> None: + def update_skill(self, + assistant_id: str, + skill_id: str, + *, + name: str = None, + description: str = None, + workspace: dict = None, + dialog_settings: dict = None, + search_settings: 'SearchSettings' = None, + **kwargs) -> DetailedResponse: + """ + Update skill. + + Update a skill with new or modified data. + **Note:** The update is performed asynchronously; you can see the status of the + update by calling the **Get skill** method and checking the value of the + **status** property. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the Watson Assistant user interface, open the skill settings and click + **API Details**. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object """ - Initialize a ChannelTransferInfo object. - :param ChannelTransferTarget target: An object specifying target channels - available for the transfer. Each property of this object represents an - available transfer target. Currently, the only supported property is - **chat**, representing the web chat integration. - """ - self.target = target + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + if search_settings is not None: + search_settings = convert_model(search_settings) + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_skill') + headers.update(sdk_headers) - @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': - """Initialize a ChannelTransferInfo object from a json dictionary.""" - args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) - else: - raise ValueError( - 'Required property \'target\' not present in ChannelTransferInfo JSON' - ) - return cls(**args) + params = { + 'version': self.version, + } - @classmethod - def _from_dict(cls, _dict): - """Initialize a ChannelTransferInfo object from a json dictionary.""" - return cls.from_dict(_dict) + data = { + 'name': name, + 'description': description, + 'workspace': workspace, + 'dialog_settings': dialog_settings, + 'search_settings': search_settings, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target.to_dict() - return _dict + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) - def __str__(self) -> str: - """Return a `str` version of this ChannelTransferInfo object.""" - return json.dumps(self.to_dict(), indent=2) + response = self.send(request, **kwargs) + return response - def __eq__(self, other: 'ChannelTransferInfo') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + def export_skills(self, + assistant_id: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Export skills. + + Asynchronously export the action skill and dialog skill (if enabled) for the + assistant. Use this method to save all skill data so that you can import it to a + different assistant using the **Import skills** method. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. + After the initial request is submitted, you can poll the status of the operation + by calling the same request again and checking the value of the **status** + property. If an error occurs (indicated by a **status** value of `Failed`), the + `status_description` property provides more information about the error, and the + `status_errors` property contains an array of error messages that caused the + failure. + When processing has completed, the request returns the exported JSON data. + Remember that the usual rate limits apply. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsExport` object + """ - def __ne__(self, other: 'ChannelTransferInfo') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='export_skills') + headers.update(sdk_headers) + params = { + 'version': self.version, + 'include_audit': include_audit, + } -class ChannelTransferTarget(): - """ - An object specifying target channels available for the transfer. Each property of this - object represents an available transfer target. Currently, the only supported property - is **chat**, representing the web chat integration. + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. - """ + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_export'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: - """ - Initialize a ChannelTransferTarget object. + response = self.send(request, **kwargs) + return response - :param ChannelTransferTargetChat chat: (optional) Information for - transferring to the web chat integration. + def import_skills(self, + assistant_id: str, + assistant_skills: List['SkillImport'], + assistant_state: 'AssistantState', + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: """ - self.chat = chat + Import skills. + + Asynchronously import skills into an existing assistant from a previously exported + file. + The request body for this method should contain the response data that was + received from a previous call to the **Export skills** method, without + modification. + A successful call to this method initiates an asynchronous import. The updated + skills belonging to the assistant are not available until processing completes. To + check the status of the asynchronous import operation, use the **Get status of + skills import** method. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param List[SkillImport] assistant_skills: An array of objects describing + the skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if assistant_skills is None: + raise ValueError('assistant_skills must be provided') + if assistant_state is None: + raise ValueError('assistant_state must be provided') + assistant_skills = [convert_model(x) for x in assistant_skills] + assistant_state = convert_model(assistant_state) + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + } + + data = { + 'assistant_skills': assistant_skills, + 'assistant_state': assistant_state, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def import_skills_status(self, assistant_id: str, + **kwargs) -> DetailedResponse: + """ + Get status of skills import. + + Retrieve the status of an asynchronous import operation previously initiated by + using the **Import skills** method. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills_status') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import/status'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + +class ListAssistantsEnums: + """ + Enums for list_assistants parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned assistants will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' + + +class ListEnvironmentsEnums: + """ + Enums for list_environments parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned environments will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' + + +class ListReleasesEnums: + """ + Enums for list_releases parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned workspaces will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' + + +############################################################################## +# Models +############################################################################## + + +class AgentAvailabilityMessage(): + """ + AgentAvailabilityMessage. + + :attr str message: (optional) The text of the message. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a AgentAvailabilityMessage object. + + :param str message: (optional) The text of the message. + """ + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': - """Initialize a ChannelTransferTarget object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if 'message' in _dict: + args['message'] = _dict.get('message') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferTarget object from a json dictionary.""" + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'chat') and self.chat is not None: - _dict['chat'] = self.chat.to_dict() + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -963,53 +1851,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferTarget object.""" + """Return a `str` version of this AgentAvailabilityMessage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferTarget') -> bool: + def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ChannelTransferTarget') -> bool: + def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ChannelTransferTargetChat(): +class AssistantCollection(): """ - Information for transferring to the web chat integration. + AssistantCollection. - :attr str url: (optional) The URL of the target web chat. + :attr List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, *, url: str = None) -> None: + def __init__(self, assistants: List['AssistantData'], + pagination: 'Pagination') -> None: """ - Initialize a ChannelTransferTargetChat object. + Initialize a AssistantCollection object. - :param str url: (optional) The URL of the target web chat. + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.url = url + self.assistants = assistants + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': - """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantCollection': + """Initialize a AssistantCollection object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if 'assistants' in _dict: + args['assistants'] = [ + AssistantData.from_dict(v) for v in _dict.get('assistants') + ] + else: + raise ValueError( + 'Required property \'assistants\' not present in AssistantCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in AssistantCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + """Initialize a AssistantCollection object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url + if hasattr(self, 'assistants') and self.assistants is not None: + assistants_list = [] + for v in self.assistants: + if isinstance(v, dict): + assistants_list.append(v) + else: + assistants_list.append(v.to_dict()) + _dict['assistants'] = assistants_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -1017,95 +1936,125 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferTargetChat object.""" + """Return a `str` version of this AssistantCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferTargetChat') -> bool: + def __eq__(self, other: 'AssistantCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: + def __ne__(self, other: 'AssistantCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogLogMessage(): +class AssistantData(): """ - Dialog log message details. + AssistantData. - :attr str level: The severity of the log message. - :attr str message: The text of the log message. - :attr str code: A code that indicates the category to which the error message - belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog - element that generated the error message. + :attr str assistant_id: (optional) The unique identifier of the assistant. + :attr str name: (optional) The name of the assistant. This string cannot contain + carriage return, newline, or tab characters. + :attr str description: (optional) The description of the assistant. This string + cannot contain carriage return, newline, or tab characters. + :attr str language: The language of the assistant. + :attr List[AssistantSkill] assistant_skills: (optional) An array of skill + references identifying the skills associated with the assistant. + :attr List[EnvironmentReference] assistant_environments: (optional) An array of + objects describing the environments defined for the assistant. """ - def __init__(self, - level: str, - message: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__( + self, + language: str, + *, + assistant_id: str = None, + name: str = None, + description: str = None, + assistant_skills: List['AssistantSkill'] = None, + assistant_environments: List['EnvironmentReference'] = None + ) -> None: """ - Initialize a DialogLogMessage object. + Initialize a AssistantData object. - :param str level: The severity of the log message. - :param str message: The text of the log message. - :param str code: A code that indicates the category to which the error - message belongs. - :param LogMessageSource source: (optional) An object that identifies the - dialog element that generated the error message. + :param str language: The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. """ - self.level = level - self.message = message - self.code = code - self.source = source + self.assistant_id = assistant_id + self.name = name + self.description = description + self.language = language + self.assistant_skills = assistant_skills + self.assistant_environments = assistant_environments @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': - """Initialize a DialogLogMessage object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantData': + """Initialize a AssistantData object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - else: - raise ValueError( - 'Required property \'level\' not present in DialogLogMessage JSON' - ) - if 'message' in _dict: - args['message'] = _dict.get('message') - else: - raise ValueError( - 'Required property \'message\' not present in DialogLogMessage JSON' - ) - if 'code' in _dict: - args['code'] = _dict.get('code') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'language' in _dict: + args['language'] = _dict.get('language') else: raise ValueError( - 'Required property \'code\' not present in DialogLogMessage JSON' + 'Required property \'language\' not present in AssistantData JSON' ) - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if 'assistant_skills' in _dict: + args['assistant_skills'] = [ + AssistantSkill.from_dict(v) + for v in _dict.get('assistant_skills') + ] + if 'assistant_environments' in _dict: + args['assistant_environments'] = [ + EnvironmentReference.from_dict(v) + for v in _dict.get('assistant_environments') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogLogMessage object from a json dictionary.""" + """Initialize a AssistantData object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'assistant_skills') and getattr( + self, 'assistant_skills') is not None: + assistant_skills_list = [] + for v in getattr(self, 'assistant_skills'): + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, 'assistant_environments') and getattr( + self, 'assistant_environments') is not None: + assistant_environments_list = [] + for v in getattr(self, 'assistant_environments'): + if isinstance(v, dict): + assistant_environments_list.append(v) + else: + assistant_environments_list.append(v.to_dict()) + _dict['assistant_environments'] = assistant_environments_list return _dict def _to_dict(self): @@ -1113,110 +2062,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogLogMessage object.""" + """Return a `str` version of this AssistantData object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogLogMessage') -> bool: + def __eq__(self, other: 'AssistantData') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogLogMessage') -> bool: + def __ne__(self, other: 'AssistantData') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LevelEnum(str, Enum): - """ - The severity of the log message. - """ - INFO = 'info' - ERROR = 'error' - WARN = 'warn' - -class DialogNodeAction(): +class AssistantSkill(): """ - DialogNodeAction. + AssistantSkill. - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result - of the action is stored. - :attr str credentials: (optional) The name of the context variable that the - client application will use to pass in credentials for the action. + :attr str skill_id: The skill ID of the skill. + :attr str type: (optional) The type of the skill. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__(self, skill_id: str, *, type: str = None) -> None: """ - Initialize a DialogNodeAction object. + Initialize a AssistantSkill object. - :param str name: The name of the action. - :param str result_variable: The location in the dialog context where the - result of the action is stored. - :param str type: (optional) The type of action to invoke. - :param dict parameters: (optional) A map of key/value pairs to be provided - to the action. - :param str credentials: (optional) The name of the context variable that - the client application will use to pass in credentials for the action. + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. """ - self.name = name + self.skill_id = skill_id self.type = type - self.parameters = parameters - self.result_variable = result_variable - self.credentials = credentials @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': - """Initialize a DialogNodeAction object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantSkill': + """Initialize a AssistantSkill object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') else: raise ValueError( - 'Required property \'name\' not present in DialogNodeAction JSON' + 'Required property \'skill_id\' not present in AssistantSkill JSON' ) if 'type' in _dict: args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') - else: - raise ValueError( - 'Required property \'result_variable\' not present in DialogNodeAction JSON' - ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeAction object from a json dictionary.""" + """Initialize a AssistantSkill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'parameters') and self.parameters is not None: - _dict['parameters'] = self.parameters - if hasattr(self, - 'result_variable') and self.result_variable is not None: - _dict['result_variable'] = self.result_variable - if hasattr(self, 'credentials') and self.credentials is not None: - _dict['credentials'] = self.credentials return _dict def _to_dict(self): @@ -1224,63 +2127,83 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeAction object.""" + """Return a `str` version of this AssistantSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeAction') -> bool: + def __eq__(self, other: 'AssistantSkill') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeAction') -> bool: + def __ne__(self, other: 'AssistantSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TypeEnum(str, Enum): """ - The type of action to invoke. + The type of the skill. """ - CLIENT = 'client' - SERVER = 'server' - WEB_ACTION = 'web-action' - CLOUD_FUNCTION = 'cloud-function' + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' -class DialogNodeOutputConnectToAgentTransferInfo(): +class AssistantState(): """ - Routing or other contextual information to be used by target service desk systems. + Status information about the skills for the assistant. Included in responses only if + **status**=`Available`. - :attr dict target: (optional) + :attr bool action_disabled: Whether the action skill is disabled in the draft + environment. + :attr bool dialog_disabled: Whether the dialog skill is disabled in the draft + environment. """ - def __init__(self, *, target: dict = None) -> None: + def __init__(self, action_disabled: bool, dialog_disabled: bool) -> None: """ - Initialize a DialogNodeOutputConnectToAgentTransferInfo object. + Initialize a AssistantState object. - :param dict target: (optional) + :param bool action_disabled: Whether the action skill is disabled in the + draft environment. + :param bool dialog_disabled: Whether the dialog skill is disabled in the + draft environment. """ - self.target = target + self.action_disabled = action_disabled + self.dialog_disabled = dialog_disabled @classmethod - def from_dict(cls, - _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': - """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantState': + """Initialize a AssistantState object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if 'action_disabled' in _dict: + args['action_disabled'] = _dict.get('action_disabled') + else: + raise ValueError( + 'Required property \'action_disabled\' not present in AssistantState JSON' + ) + if 'dialog_disabled' in _dict: + args['dialog_disabled'] = _dict.get('dialog_disabled') + else: + raise ValueError( + 'Required property \'dialog_disabled\' not present in AssistantState JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + """Initialize a AssistantState object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target + if hasattr(self, + 'action_disabled') and self.action_disabled is not None: + _dict['action_disabled'] = self.action_disabled + if hasattr(self, + 'dialog_disabled') and self.dialog_disabled is not None: + _dict['dialog_disabled'] = self.dialog_disabled return _dict def _to_dict(self): @@ -1288,75 +2211,60 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" + """Return a `str` version of this AssistantState object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + def __eq__(self, other: 'AssistantState') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, - other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + def __ne__(self, other: 'AssistantState') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeOutputOptionsElement(): +class BaseEnvironmentOrchestration(): """ - DialogNodeOutputOptionsElement. + The search skill orchestration settings for the environment. - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message - input to be sent to the assistant if the user selects the corresponding option. + :attr bool search_skill_fallback: (optional) Whether assistants deployed to the + environment fall back to a search skill when responding to messages that do not + match any intent. If no search skill is configured for the assistant, this + property is ignored. """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__(self, *, search_skill_fallback: bool = None) -> None: """ - Initialize a DialogNodeOutputOptionsElement object. + Initialize a BaseEnvironmentOrchestration object. - :param str label: The user-facing label for the option. - :param DialogNodeOutputOptionsElementValue value: An object defining the - message input to be sent to the assistant if the user selects the - corresponding option. + :param bool search_skill_fallback: (optional) Whether assistants deployed + to the environment fall back to a search skill when responding to messages + that do not match any intent. If no search skill is configured for the + assistant, this property is ignored. """ - self.label = label - self.value = value + self.search_skill_fallback = search_skill_fallback @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': - """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentOrchestration': + """Initialize a BaseEnvironmentOrchestration object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - else: - raise ValueError( - 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' - ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) - else: - raise ValueError( - 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' - ) + if 'search_skill_fallback' in _dict: + args['search_skill_fallback'] = _dict.get('search_skill_fallback') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + """Initialize a BaseEnvironmentOrchestration object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, '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, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback return _dict def _to_dict(self): @@ -1364,56 +2272,53 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputOptionsElement object.""" + """Return a `str` version of this BaseEnvironmentOrchestration object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> bool: + def __eq__(self, other: 'BaseEnvironmentOrchestration') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: + def __ne__(self, other: 'BaseEnvironmentOrchestration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeOutputOptionsElementValue(): +class BaseEnvironmentReleaseReference(): """ - An object defining the message input to be sent to the assistant if the user selects - the corresponding option. + An object describing the release that is currently deployed in the environment. - :attr MessageInput input: (optional) An input object that includes the input - text. + :attr str release: (optional) The name of the deployed release. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__(self, *, release: str = None) -> None: """ - Initialize a DialogNodeOutputOptionsElementValue object. + Initialize a BaseEnvironmentReleaseReference object. - :param MessageInput input: (optional) An input object that includes the - input text. + :param str release: (optional) The name of the deployed release. """ - self.input = input + self.release = release @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': - """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentReleaseReference': + """Initialize a BaseEnvironmentReleaseReference object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if 'release' in _dict: + args['release'] = _dict.get('release') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" + """Initialize a BaseEnvironmentReleaseReference object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if hasattr(self, 'release') and self.release is not None: + _dict['release'] = self.release return _dict def _to_dict(self): @@ -1421,75 +2326,96 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" + """Return a `str` version of this BaseEnvironmentReleaseReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: + def __eq__(self, other: 'BaseEnvironmentReleaseReference') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: + def __ne__(self, other: 'BaseEnvironmentReleaseReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeVisited(): +class BulkClassifyOutput(): """ - An objects containing detailed diagnostic information about a dialog node that was - triggered during processing of the input message. + BulkClassifyOutput. - :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. + :attr BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :attr List[RuntimeEntity] entities: (optional) An array of entities identified + in the utterance. + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + the utterance. """ def __init__(self, *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + input: 'BulkClassifyUtterance' = None, + entities: List['RuntimeEntity'] = None, + intents: List['RuntimeIntent'] = None) -> None: """ - Initialize a DialogNodeVisited object. + Initialize a BulkClassifyOutput 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. + :param BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the utterance. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the utterance. """ - self.dialog_node = dialog_node - self.title = title - self.conditions = conditions + self.input = input + self.entities = entities + self.intents = intents @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': - """Initialize a DialogNodeVisited object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': + """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if 'input' in _dict: + args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeVisited object from a json dictionary.""" + """Initialize a BulkClassifyOutput object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'conditions') and self.conditions is not None: - _dict['conditions'] = self.conditions + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list return _dict def _to_dict(self): @@ -1497,89 +2423,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeVisited object.""" + """Return a `str` version of this BulkClassifyOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeVisited') -> bool: + def __eq__(self, other: 'BulkClassifyOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogNodeVisited') -> bool: + def __ne__(self, other: 'BulkClassifyOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogSuggestion(): +class BulkClassifyResponse(): """ - DialogSuggestion. + BulkClassifyResponse. - :attr str label: The user-facing label for the suggestion. This label is taken - from the **title** or **user_label** property of the corresponding dialog node, - depending on the disambiguation options. - :attr DialogSuggestionValue value: An object defining the message input to be - sent to the assistant if the user selects the corresponding disambiguation - option. - :attr dict output: (optional) The dialog output that will be returned from the - Watson Assistant service if the user selects the corresponding option. + :attr List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None) -> None: + def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: """ - Initialize a DialogSuggestion object. + Initialize a BulkClassifyResponse object. - :param str label: The user-facing label for the suggestion. This label is - taken from the **title** or **user_label** property of the corresponding - dialog node, depending on the disambiguation options. - :param DialogSuggestionValue value: An object defining the message input to - be sent to the assistant if the user selects the corresponding - disambiguation option. - :param dict output: (optional) The dialog output that will be returned from - the Watson Assistant service if the user selects the corresponding option. + :param List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. """ - self.label = label - self.value = value self.output = output @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': - """Initialize a DialogSuggestion object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': + """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - else: - raise ValueError( - 'Required property \'label\' not present in 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') + args['output'] = [ + BulkClassifyOutput.from_dict(v) for v in _dict.get('output') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestion object from a json dictionary.""" + """Initialize a BulkClassifyResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output + output_list = [] + for v in self.output: + if isinstance(v, dict): + output_list.append(v) + else: + output_list.append(v.to_dict()) + _dict['output'] = output_list return _dict def _to_dict(self): @@ -1587,56 +2487,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogSuggestion object.""" + """Return a `str` version of this BulkClassifyResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogSuggestion') -> bool: + def __eq__(self, other: 'BulkClassifyResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogSuggestion') -> bool: + def __ne__(self, other: 'BulkClassifyResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogSuggestionValue(): +class BulkClassifyUtterance(): """ - An object defining the message input to be sent to the assistant if the user selects - the corresponding disambiguation option. + The user input utterance to classify. - :attr MessageInput input: (optional) An input object that includes the input - text. + :attr str text: The text of the input utterance. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__(self, text: str) -> None: """ - Initialize a DialogSuggestionValue object. + Initialize a BulkClassifyUtterance object. - :param MessageInput input: (optional) An input object that includes the - input text. + :param str text: The text of the input utterance. """ - self.input = input + self.text = text @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': - """Initialize a DialogSuggestionValue object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': + """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in BulkClassifyUtterance JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestionValue object from a json dictionary.""" + """Initialize a BulkClassifyUtterance object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text return _dict def _to_dict(self): @@ -1644,183 +2545,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogSuggestionValue object.""" + """Return a `str` version of this BulkClassifyUtterance object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogSuggestionValue') -> bool: + def __eq__(self, other: 'BulkClassifyUtterance') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DialogSuggestionValue') -> bool: + def __ne__(self, other: 'BulkClassifyUtterance') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Log(): +class CaptureGroup(): """ - Log. + CaptureGroup. - :attr str log_id: A unique identifier for the logged event. - :attr MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :attr MessageResponse response: A response from the Watson Assistant service. - :attr str assistant_id: Unique identifier of the assistant. - :attr str session_id: The ID of the session the message was part of. - :attr str skill_id: The unique identifier of the skill that responded to the - message. - :attr str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the - message. - :attr str language: The language of the assistant to which the message request - was made. - :attr str customer_id: (optional) The customer ID specified for the message, if - any. + :attr str 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, - log_id: str, - request: 'MessageRequest', - response: 'MessageResponse', - assistant_id: str, - session_id: str, - skill_id: str, - snapshot: str, - request_timestamp: str, - response_timestamp: str, - language: str, - *, - customer_id: str = None) -> None: + def __init__(self, group: str, *, location: List[int] = None) -> None: """ - Initialize a Log object. + Initialize a CaptureGroup object. - :param str log_id: A unique identifier for the logged event. - :param MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :param MessageResponse response: A response from the Watson Assistant - service. - :param str assistant_id: Unique identifier of the assistant. - :param str session_id: The ID of the session the message was part of. - :param str skill_id: The unique identifier of the skill that responded to - the message. - :param str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :param str request_timestamp: The timestamp for receipt of the message. - :param str response_timestamp: The timestamp for the system response to the - message. - :param str language: The language of the assistant to which the message - request was made. - :param str customer_id: (optional) The customer ID specified for the - message, if any. + :param str 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.log_id = log_id - self.request = request - self.response = response - self.assistant_id = assistant_id - self.session_id = session_id - self.skill_id = skill_id - self.snapshot = snapshot - self.request_timestamp = request_timestamp - self.response_timestamp = response_timestamp - self.language = language - self.customer_id = customer_id + self.group = group + self.location = location @classmethod - def from_dict(cls, _dict: Dict) -> 'Log': - """Initialize a Log object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': + """Initialize a CaptureGroup object from a json dictionary.""" args = {} - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') - else: - raise ValueError( - 'Required property \'log_id\' not present in Log JSON') - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) - else: - raise ValueError( - 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) - else: - raise ValueError( - 'Required property \'response\' not present in Log JSON') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - else: - raise ValueError( - 'Required property \'assistant_id\' not present in Log JSON') - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') - else: - raise ValueError( - 'Required property \'session_id\' not present in Log JSON') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - else: - raise ValueError( - 'Required property \'skill_id\' not present in Log JSON') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - else: - raise ValueError( - 'Required property \'snapshot\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') - else: - raise ValueError( - 'Required property \'request_timestamp\' not present in Log JSON' - ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') - else: - raise ValueError( - 'Required property \'response_timestamp\' not present in Log JSON' - ) - if 'language' in _dict: - args['language'] = _dict.get('language') + if 'group' in _dict: + args['group'] = _dict.get('group') else: raise ValueError( - 'Required property \'language\' not present in Log JSON') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') + 'Required property \'group\' not present in CaptureGroup JSON') + if 'location' in _dict: + args['location'] = _dict.get('location') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Log object from a json dictionary.""" + """Initialize a CaptureGroup object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'log_id') and self.log_id is not None: - _dict['log_id'] = self.log_id - if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request.to_dict() - if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response.to_dict() - if hasattr(self, 'assistant_id') and self.assistant_id is not None: - _dict['assistant_id'] = self.assistant_id - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id - if hasattr(self, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot - if hasattr(self, - 'request_timestamp') and self.request_timestamp is not None: - _dict['request_timestamp'] = self.request_timestamp - if hasattr( - self, - 'response_timestamp') and self.response_timestamp is not None: - _dict['response_timestamp'] = self.response_timestamp - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id + if hasattr(self, 'group') and self.group is not None: + _dict['group'] = self.group + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location return _dict def _to_dict(self): @@ -1828,69 +2611,68 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Log object.""" + """Return a `str` version of this CaptureGroup object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Log') -> bool: + def __eq__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Log') -> bool: + def __ne__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogCollection(): +class ChannelTransferInfo(): """ - LogCollection. + Information used by an integration to transfer the conversation to a different + channel. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :attr ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an available + transfer target. Currently, the only supported property is **chat**, + representing the web chat integration. """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__(self, target: 'ChannelTransferTarget') -> None: """ - Initialize a LogCollection object. + Initialize a ChannelTransferInfo object. - :param List[Log] logs: An array of objects describing log events. - :param LogPagination pagination: The pagination data for the returned - objects. + :param ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an + available transfer target. Currently, the only supported property is + **chat**, representing the web chat integration. """ - self.logs = logs - self.pagination = pagination + self.target = target @classmethod - def from_dict(cls, _dict: Dict) -> 'LogCollection': - """Initialize a LogCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': + """Initialize a ChannelTransferInfo object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] - else: - raise ValueError( - 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + if 'target' in _dict: + args['target'] = ChannelTransferTarget.from_dict( + _dict.get('target')) else: raise ValueError( - 'Required property \'pagination\' not present in LogCollection JSON' + 'Required property \'target\' not present in ChannelTransferInfo JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogCollection object from a json dictionary.""" + """Initialize a ChannelTransferInfo object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, '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() + if hasattr(self, 'target') and self.target is not None: + if isinstance(self.target, dict): + _dict['target'] = self.target + else: + _dict['target'] = self.target.to_dict() return _dict def _to_dict(self): @@ -1898,134 +2680,61 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogCollection object.""" + """Return a `str` version of this ChannelTransferInfo object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogCollection') -> bool: + def __eq__(self, other: 'ChannelTransferInfo') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogCollection') -> bool: + def __ne__(self, other: 'ChannelTransferInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSource(): - """ - An object that identifies the dialog element that generated the error message. - - """ - - def __init__(self) -> None: - """ - Initialize a LogMessageSource object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSource': - """Initialize a LogMessageSource object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a LogMessageSource object from a json dictionary.""" - return cls.from_dict(_dict) - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['dialog_node'] = 'LogMessageSourceDialogNode' - mapping['action'] = 'LogMessageSourceAction' - mapping['step'] = 'LogMessageSourceStep' - mapping['handler'] = 'LogMessageSourceHandler' - disc_value = _dict.get('type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'type\' not found in LogMessageSource JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class LogPagination(): +class ChannelTransferTarget(): """ - The pagination data for the returned objects. + An object specifying target channels available for the transfer. Each property of this + object represents an available transfer target. Currently, the only supported property + is **chat**, representing the web chat integration. - :attr str next_url: (optional) The URL that will return the next page of - results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + :attr ChannelTransferTargetChat chat: (optional) Information for transferring to + the web chat integration. """ - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: """ - Initialize a LogPagination object. + Initialize a ChannelTransferTarget object. - :param str next_url: (optional) The URL that will return the next page of - results, if any. - :param int matched: (optional) Reserved for future use. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param ChannelTransferTargetChat chat: (optional) Information for + transferring to the web chat integration. """ - self.next_url = next_url - self.matched = matched - self.next_cursor = next_cursor + self.chat = chat @classmethod - def from_dict(cls, _dict: Dict) -> 'LogPagination': - """Initialize a LogPagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': + """Initialize a ChannelTransferTarget object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if 'chat' in _dict: + args['chat'] = ChannelTransferTargetChat.from_dict( + _dict.get('chat')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogPagination object from a json dictionary.""" + """Initialize a ChannelTransferTarget object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'chat') and self.chat is not None: + if isinstance(self.chat, dict): + _dict['chat'] = self.chat + else: + _dict['chat'] = self.chat.to_dict() return _dict def _to_dict(self): @@ -2033,87 +2742,53 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogPagination object.""" + """Return a `str` version of this ChannelTransferTarget object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogPagination') -> bool: + def __eq__(self, other: 'ChannelTransferTarget') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogPagination') -> bool: + def __ne__(self, other: 'ChannelTransferTarget') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContext(): +class ChannelTransferTargetChat(): """ - MessageContext. + Information for transferring to the web chat integration. - :attr MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :attr object integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :attr str url: (optional) The URL of the target web chat. """ - def __init__(self, - *, - global_: 'MessageContextGlobal' = None, - skills: dict = None, - integrations: object = None) -> None: + def __init__(self, *, url: str = None) -> None: """ - Initialize a MessageContext object. + Initialize a ChannelTransferTargetChat object. - :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :param object integrations: (optional) An object containing context data - that is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str url: (optional) The URL of the target web chat. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.url = url @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContext': - """Initialize a MessageContext object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': + """Initialize a ChannelTransferTargetChat object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobal.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if 'url' in _dict: + args['url'] = _dict.get('url') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContext object from a json dictionary.""" + """Initialize a ChannelTransferTargetChat object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url return _dict def _to_dict(self): @@ -2121,66 +2796,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContext object.""" + """Return a `str` version of this ChannelTransferTargetChat object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContext') -> bool: + def __eq__(self, other: 'ChannelTransferTargetChat') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContext') -> bool: + def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobal(): +class DialogLogMessage(): """ - Session context data that is shared by all skills used by the assistant. + Dialog log message details. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The session ID. + :attr str level: The severity of the log message. + :attr str message: The text of the log message. + :attr str code: A code that indicates the category to which the error message + belongs. + :attr LogMessageSource source: (optional) An object that identifies the dialog + element that generated the error message. """ def __init__(self, + level: str, + message: str, + code: str, *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + source: 'LogMessageSource' = None) -> None: """ - Initialize a MessageContextGlobal object. + Initialize a DialogLogMessage object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error + message belongs. + :param LogMessageSource source: (optional) An object that identifies the + dialog element that generated the error message. """ - self.system = system - self.session_id = session_id + self.level = level + self.message = message + self.code = code + self.source = source @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': - """Initialize a MessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': + """Initialize a DialogLogMessage object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if 'level' in _dict: + args['level'] = _dict.get('level') + else: + raise ValueError( + 'Required property \'level\' not present in DialogLogMessage JSON' + ) + if 'message' in _dict: + args['message'] = _dict.get('message') + else: + raise ValueError( + 'Required property \'message\' not present in DialogLogMessage JSON' + ) + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError( + 'Required property \'code\' not present in DialogLogMessage JSON' + ) + if 'source' in _dict: + args['source'] = LogMessageSource.from_dict(_dict.get('source')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobal object from a json dictionary.""" + """Initialize a DialogLogMessage object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and getattr(self, - 'session_id') is not None: - _dict['session_id'] = getattr(self, 'session_id') + if hasattr(self, 'level') and self.level is not None: + _dict['level'] = self.level + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -2188,66 +2895,110 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobal object.""" + """Return a `str` version of this DialogLogMessage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobal') -> bool: + def __eq__(self, other: 'DialogLogMessage') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobal') -> bool: + def __ne__(self, other: 'DialogLogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LevelEnum(str, Enum): + """ + The severity of the log message. + """ + INFO = 'info' + ERROR = 'error' + WARN = 'warn' + -class MessageContextGlobalStateless(): +class DialogNodeAction(): """ - Session context data that is shared by all skills used by the assistant. + DialogNodeAction. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The unique identifier of the session. + :attr str name: The name of the action. + :attr str type: (optional) The type of action to invoke. + :attr dict parameters: (optional) A map of key/value pairs to be provided to the + action. + :attr str result_variable: The location in the dialog context where the result + of the action is stored. + :attr str credentials: (optional) The name of the context variable that the + client application will use to pass in credentials for the action. """ def __init__(self, + name: str, + result_variable: str, *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + type: str = None, + parameters: dict = None, + credentials: str = None) -> None: """ - Initialize a MessageContextGlobalStateless object. + Initialize a DialogNodeAction object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str name: The name of the action. + :param str result_variable: The location in the dialog context where the + result of the action is stored. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided + to the action. + :param str credentials: (optional) The name of the context variable that + the client application will use to pass in credentials for the action. """ - self.system = system - self.session_id = session_id + self.name = name + self.type = type + self.parameters = parameters + self.result_variable = result_variable + self.credentials = credentials @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': + """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in DialogNodeAction JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'parameters' in _dict: + args['parameters'] = _dict.get('parameters') + if 'result_variable' in _dict: + args['result_variable'] = _dict.get('result_variable') + else: + raise ValueError( + 'Required property \'result_variable\' not present in DialogNodeAction JSON' + ) + if 'credentials' in _dict: + args['credentials'] = _dict.get('credentials') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + """Initialize a DialogNodeAction object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'parameters') and self.parameters is not None: + _dict['parameters'] = self.parameters + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'credentials') and self.credentials is not None: + _dict['credentials'] = self.credentials return _dict def _to_dict(self): @@ -2255,194 +3006,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalStateless object.""" + """Return a `str` version of this DialogNodeAction object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: + def __eq__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: + def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of action to invoke. + """ + CLIENT = 'client' + SERVER = 'server' + WEB_ACTION = 'web-action' + CLOUD_FUNCTION = 'cloud-function' + -class MessageContextGlobalSystem(): +class DialogNodeOutputConnectToAgentTransferInfo(): """ - Built-in system properties that apply to all skills used by the assistant. + Routing or other contextual information to be used by target service desk systems. - :attr str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root of - the message body. If **user_id** is specified in both locations in a message - request, the value specified at the root is used. - :attr int turn_count: (optional) A counter that is automatically incremented - with each turn of the conversation. A value of 1 indicates that this is the the - first turn of a new conversation, which can affect the behavior of some skills - (for example, triggering the start node of a dialog). - :attr str locale: (optional) The language code for localization in the user - input. The specified locale overrides the default for the assistant, and is used - for interpreting entity values in user input such as date values. For example, - `04/03/2018` might be interpreted either as April 3 or March 4, depending on the - locale. - This property is included only if the new system entities are enabled for the - skill. - :attr str reference_time: (optional) The base time for interpreting any relative - time mentions in the user input. The specified time overrides the current server - time, and is used to calculate times mentioned in relative terms such as `now` - or `tomorrow`. This can be useful for simulating past or future times for - testing purposes, or when analyzing documents such as news articles. - This value must be a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for the - skill. - :attr str session_start_time: (optional) The time at which the session started. - With the stateful `message` method, the start time is always present, and is set - by the service based on the time the session was created. With the stateless - `message` method, the start time is set by the service in the response to the - first message, and should be returned as part of the context with each - subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for example, - `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :attr str state: (optional) An encoded string that represents the configuration - state of the assistant at the beginning of the conversation. If you are using - the stateless `message` method, save this value and then send it in the context - of the subsequent message request to avoid disruptions if there are - configuration changes during the conversation (such as a change to a skill the - assistant uses). - :attr bool skip_user_input: (optional) For internal use only. + :attr dict target: (optional) """ - def __init__(self, - *, - timezone: str = None, - user_id: str = None, - turn_count: int = None, - locale: str = None, - reference_time: str = None, - session_start_time: str = None, - state: str = None, - skip_user_input: bool = None) -> None: + def __init__(self, *, target: dict = None) -> None: """ - Initialize a MessageContextGlobalSystem object. + Initialize a DialogNodeOutputConnectToAgentTransferInfo object. - :param str timezone: (optional) The user time zone. The assistant uses the - time zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root - of the message body. If **user_id** is specified in both locations in a - message request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically - incremented with each turn of the conversation. A value of 1 indicates that - this is the the first turn of a new conversation, which can affect the - behavior of some skills (for example, triggering the start node of a - dialog). - :param str locale: (optional) The language code for localization in the - user input. The specified locale overrides the default for the assistant, - and is used for interpreting entity values in user input such as date - values. For example, `04/03/2018` might be interpreted either as April 3 or - March 4, depending on the locale. - This property is included only if the new system entities are enabled for - the skill. - :param str reference_time: (optional) The base time for interpreting any - relative time mentions in the user input. The specified time overrides the - current server time, and is used to calculate times mentioned in relative - terms such as `now` or `tomorrow`. This can be useful for simulating past - or future times for testing purposes, or when analyzing documents such as - news articles. - This value must be a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for - the skill. - :param str session_start_time: (optional) The time at which the session - started. With the stateful `message` method, the start time is always - present, and is set by the service based on the time the session was - created. With the stateless `message` method, the start time is set by the - service in the response to the first message, and should be returned as - part of the context with each subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the - configuration state of the assistant at the beginning of the conversation. - If you are using the stateless `message` method, save this value and then - send it in the context of the subsequent message request to avoid - disruptions if there are configuration changes during the conversation - (such as a change to a skill the assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param dict target: (optional) """ - self.timezone = timezone - self.user_id = user_id - self.turn_count = turn_count - self.locale = locale - self.reference_time = reference_time - self.session_start_time = session_start_time - self.state = state - self.skip_user_input = skip_user_input + self.target = target @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': + """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - if 'turn_count' in _dict: - args['turn_count'] = _dict.get('turn_count') - if 'locale' in _dict: - args['locale'] = _dict.get('locale') - if 'reference_time' in _dict: - args['reference_time'] = _dict.get('reference_time') - if 'session_start_time' in _dict: - args['session_start_time'] = _dict.get('session_start_time') - if 'state' in _dict: - args['state'] = _dict.get('state') - if 'skip_user_input' in _dict: - args['skip_user_input'] = _dict.get('skip_user_input') + if 'target' in _dict: + args['target'] = _dict.get('target') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - if hasattr(self, 'turn_count') and self.turn_count is not None: - _dict['turn_count'] = self.turn_count - if hasattr(self, 'locale') and self.locale is not None: - _dict['locale'] = self.locale - if hasattr(self, 'reference_time') and self.reference_time is not None: - _dict['reference_time'] = self.reference_time - if hasattr( - self, - 'session_start_time') and self.session_start_time is not None: - _dict['session_start_time'] = self.session_start_time - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - if hasattr(self, - 'skip_user_input') and self.skip_user_input is not None: - _dict['skip_user_input'] = self.skip_user_input + if hasattr(self, 'target') and self.target is not None: + _dict['target'] = self.target return _dict def _to_dict(self): @@ -2450,94 +3070,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalSystem object.""" + """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + def __eq__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: + def __ne__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(str, Enum): - """ - The language code for localization in the user input. The specified locale - overrides the default for the assistant, and is used for interpreting entity - values in user input such as date values. For example, `04/03/2018` might be - interpreted either as April 3 or March 4, depending on the locale. - This property is included only if the new system entities are enabled for the - skill. - """ - EN_US = 'en-us' - EN_CA = 'en-ca' - EN_GB = 'en-gb' - AR_AR = 'ar-ar' - CS_CZ = 'cs-cz' - DE_DE = 'de-de' - ES_ES = 'es-es' - FR_FR = 'fr-fr' - IT_IT = 'it-it' - JA_JP = 'ja-jp' - KO_KR = 'ko-kr' - NL_NL = 'nl-nl' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' - -class MessageContextSkill(): +class DialogNodeOutputOptionsElement(): """ - Contains information specific to a particular skill used by the assistant. The - property name must be the same as the name of the skill (for example, `main skill`). + DialogNodeOutputOptionsElement. - :attr dict user_defined: (optional) Arbitrary variables that can be read and - written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by - the skill. + :attr str 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, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + def __init__(self, label: str, + value: 'DialogNodeOutputOptionsElementValue') -> None: """ - Initialize a MessageContextSkill object. + Initialize a DialogNodeOutputOptionsElement object. - :param dict user_defined: (optional) Arbitrary variables that can be read - and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. + :param str 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.user_defined = user_defined - self.system = system + self.label = label + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': - """Initialize a MessageContextSkill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': + """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) + if 'label' in _dict: + args['label'] = _dict.get('label') + else: + raise ValueError( + 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' + ) + if 'value' in _dict: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict( + _dict.get('value')) + else: + raise ValueError( + 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkill object from a json dictionary.""" + """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'value') and self.value is not None: + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -2545,186 +3149,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkill object.""" + """Return a `str` version of this DialogNodeOutputOptionsElement object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkill') -> bool: + def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkill') -> bool: + def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkillSystem(): +class DialogNodeOutputOptionsElementValue(): """ - System context data used by the skill. + An object defining the message input to be sent to the assistant if the user selects + the corresponding option. - :attr str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. + :attr MessageInput input: (optional) An input object that includes the input + text. """ - # The set of defined properties for the class - _properties = frozenset(['state']) - - def __init__(self, *, state: str = None, **kwargs) -> None: + def __init__(self, *, input: 'MessageInput' = None) -> None: """ - Initialize a MessageContextSkillSystem object. + Initialize a DialogNodeOutputOptionsElementValue object. - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + :param MessageInput input: (optional) An input object that includes the + input text. """ - self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.input = input @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': + """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - if 'state' in _dict: - args['state'] = _dict.get('state') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if 'input' in _dict: + args['input'] = MessageInput.from_dict(_dict.get('input')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" + """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextSkillSystem') -> bool: + def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextStateless(): +class DialogNodeVisited(): """ - MessageContextStateless. + An objects containing detailed diagnostic information about a dialog node that was + visited during processing of the input message. - :attr MessageContextGlobalStateless global_: (optional) Session context data - that is shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :attr object integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :attr str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :attr str title: (optional) The title of the dialog node. + :attr str conditions: (optional) The conditions that trigger the dialog node. """ def __init__(self, *, - global_: 'MessageContextGlobalStateless' = None, - skills: dict = None, - integrations: object = None) -> None: + dialog_node: str = None, + title: str = None, + conditions: str = None) -> None: """ - Initialize a MessageContextStateless object. + Initialize a DialogNodeVisited object. - :param MessageContextGlobalStateless global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :param object integrations: (optional) An object containing context data - that is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog + node. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.dialog_node = dialog_node + self.title = title + self.conditions = conditions @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': - """Initialize a MessageContextStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': + """Initialize a DialogNodeVisited object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobalStateless.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'conditions' in _dict: + args['conditions'] = _dict.get('conditions') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextStateless object from a json dictionary.""" + """Initialize a DialogNodeVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'conditions') and self.conditions is not None: + _dict['conditions'] = self.conditions return _dict def _to_dict(self): @@ -2732,141 +3285,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextStateless object.""" + """Return a `str` version of this DialogNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextStateless') -> bool: + def __eq__(self, other: 'DialogNodeVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageContextStateless') -> bool: + def __ne__(self, other: 'DialogNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInput(): +class DialogSuggestion(): """ - An input object that includes the input text. + DialogSuggestion. - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be sent - to external services by webhooks. - :attr MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. + :attr str label: The user-facing label for the suggestion. This label is taken + from the **title** or **user_label** property of the corresponding dialog node, + depending on the disambiguation options. + :attr DialogSuggestionValue value: An object defining the message input to be + sent to the assistant if the user selects the corresponding disambiguation + option. + **Note:** This entire message input object must be included in the request body + of the next message sent to the assistant. Do not modify or remove any of the + included properties. + :attr dict output: (optional) The dialog output that will be returned from the + Watson Assistant service if the user selects the corresponding option. """ def __init__(self, + label: str, + value: 'DialogSuggestionValue', *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptions' = None) -> None: + output: dict = None) -> None: """ - Initialize a MessageInput object. + Initialize a DialogSuggestion object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be - sent to external services by webhooks. - :param MessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param str label: The user-facing label for the suggestion. This label is + taken from the **title** or **user_label** property of the corresponding + dialog node, depending on the disambiguation options. + :param DialogSuggestionValue value: An object defining the message input to + be sent to the assistant if the user selects the corresponding + disambiguation option. + **Note:** This entire message input object must be included in the request + body of the next message sent to the assistant. Do not modify or remove any + of the included properties. + :param dict output: (optional) The dialog output that will be returned from + the Watson Assistant service if the user selects the corresponding option. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.options = options + self.label = label + self.value = value + self.output = output @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInput': - """Initialize a MessageInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': + """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(x) - for x in _dict.get('attachments') - ] - if 'options' in _dict: - args['options'] = MessageInputOptions.from_dict( - _dict.get('options')) + if '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) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInput object from a json dictionary.""" + """Initialize a DialogSuggestion object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - _dict['attachments'] = [x.to_dict() for x in self.attachments] - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'value') and self.value is not None: + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() + if hasattr(self, 'output') and self.output is not None: + _dict['output'] = self.output return _dict def _to_dict(self): @@ -2874,78 +3384,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInput object.""" + """Return a `str` version of this DialogSuggestion object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInput') -> bool: + def __eq__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInput') -> bool: + def __ne__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - TEXT = 'text' - SEARCH = 'search' - -class MessageInputAttachment(): +class DialogSuggestionValue(): """ - A reference to a media file to be sent as an attachment with the message. + An object defining the message input to be sent to the assistant if the user selects + the corresponding disambiguation option. + **Note:** This entire message input object must be included in the request body of + the next message sent to the assistant. Do not modify or remove any of the included + properties. - :attr str url: The URL of the media file. - :attr str media_type: (optional) The media content type (such as a MIME type) of - the attachment. + :attr MessageInput input: (optional) An input object that includes the input + text. """ - def __init__(self, url: str, *, media_type: str = None) -> None: + def __init__(self, *, input: 'MessageInput' = None) -> None: """ - Initialize a MessageInputAttachment object. + Initialize a DialogSuggestionValue object. - :param str url: The URL of the media file. - :param str media_type: (optional) The media content type (such as a MIME - type) of the attachment. + :param MessageInput input: (optional) An input object that includes the + input text. """ - self.url = url - self.media_type = media_type + self.input = input @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': - """Initialize a MessageInputAttachment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': + """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') - else: - raise ValueError( - 'Required property \'url\' not present in MessageInputAttachment JSON' - ) - if 'media_type' in _dict: - args['media_type'] = _dict.get('media_type') + if 'input' in _dict: + args['input'] = MessageInput.from_dict(_dict.get('input')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputAttachment object from a json dictionary.""" + """Initialize a DialogSuggestionValue object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'media_type') and self.media_type is not None: - _dict['media_type'] = self.media_type + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): @@ -2953,128 +3447,191 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputAttachment object.""" + """Return a `str` version of this DialogSuggestionValue object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputAttachment') -> bool: + def __eq__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputAttachment') -> bool: + def __ne__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptions(): - """ - Optional properties that control how the assistant responds. - - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response includes the `context` property. - If you also specify **debug**=`true`, the returned skill context includes the - `system.state` property. - :attr bool export: (optional) Whether to return session context, including full - conversation state. If you specify `true`, the response includes the `context` - property, and the skill context includes the `system.state` property. - **Note:** If **export**=`true`, the context is returned regardless of the value - of **return_context**. +class Environment(): + """ + Environment. + + :attr str name: (optional) The name of the environment. + :attr str description: (optional) The description of the environment. + :attr str assistant_id: (optional) The assistant ID of the assistant the + environment is associated with. + :attr str environment_id: (optional) The environment ID of the environment. + :attr str environment: (optional) The type of the environment. All environments + other than the `draft` and `live` environments have the type `staging`. + :attr BaseEnvironmentReleaseReference release_reference: (optional) An object + describing the release that is currently deployed in the environment. + :attr BaseEnvironmentOrchestration orchestration: (optional) The search skill + orchestration settings for the environment. + :attr int session_timeout: The session inactivity timeout setting for the + environment (in seconds). + :attr List[IntegrationReference] integration_references: (optional) An array of + objects describing the integrations that exist in the environment. + :attr List[EnvironmentSkill] skill_references: An array of objects identifying + the skills (such as action and dialog) that exist in the environment. + :attr datetime created: (optional) The timestamp for creation of the object. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__(self, + session_timeout: int, + skill_references: List['EnvironmentSkill'], *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None, - return_context: bool = None, - export: bool = None) -> None: + name: str = None, + description: str = None, + assistant_id: str = None, + environment_id: str = None, + environment: str = None, + release_reference: 'BaseEnvironmentReleaseReference' = None, + orchestration: 'BaseEnvironmentOrchestration' = None, + integration_references: List['IntegrationReference'] = None, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Environment object. + + :param int session_timeout: The session inactivity timeout setting for the + environment (in seconds). + :param List[EnvironmentSkill] skill_references: An array of objects + identifying the skills (such as action and dialog) that exist in the + environment. + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. """ - Initialize a MessageInputOptions object. - - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :param bool return_context: (optional) Whether to return session context - with the response. If you specify `true`, the response includes the - `context` property. If you also specify **debug**=`true`, the returned - skill context includes the `system.state` property. - :param bool export: (optional) Whether to return session context, including - full conversation state. If you specify `true`, the response includes the - `context` property, and the skill context includes the `system.state` - property. - **Note:** If **export**=`true`, the context is returned regardless of the - value of **return_context**. - """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug - self.return_context = return_context - self.export = export - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': - """Initialize a MessageInputOptions object from a json dictionary.""" + self.name = name + self.description = description + self.assistant_id = assistant_id + self.environment_id = environment_id + self.environment = environment + self.release_reference = release_reference + self.orchestration = orchestration + self.session_timeout = session_timeout + self.integration_references = integration_references + self.skill_references = skill_references + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Environment': + """Initialize a Environment object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') - if 'return_context' in _dict: - args['return_context'] = _dict.get('return_context') - if 'export' in _dict: - args['export'] = _dict.get('export') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'environment' in _dict: + args['environment'] = _dict.get('environment') + if 'release_reference' in _dict: + args[ + 'release_reference'] = BaseEnvironmentReleaseReference.from_dict( + _dict.get('release_reference')) + if 'orchestration' in _dict: + args['orchestration'] = BaseEnvironmentOrchestration.from_dict( + _dict.get('orchestration')) + if 'session_timeout' in _dict: + args['session_timeout'] = _dict.get('session_timeout') + else: + raise ValueError( + 'Required property \'session_timeout\' not present in Environment JSON' + ) + if 'integration_references' in _dict: + args['integration_references'] = [ + IntegrationReference.from_dict(v) + for v in _dict.get('integration_references') + ] + if 'skill_references' in _dict: + args['skill_references'] = [ + EnvironmentSkill.from_dict(v) + for v in _dict.get('skill_references') + ] + else: + raise ValueError( + 'Required property \'skill_references\' not present in Environment JSON' + ) + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptions object from a json dictionary.""" + """Initialize a Environment object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'restart') and self.restart is not None: - _dict['restart'] = self.restart + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') + if hasattr(self, 'release_reference') and getattr( + self, 'release_reference') is not None: + if isinstance(getattr(self, 'release_reference'), dict): + _dict['release_reference'] = getattr(self, 'release_reference') + else: + _dict['release_reference'] = getattr( + self, 'release_reference').to_dict() + if hasattr(self, 'orchestration') and getattr( + self, 'orchestration') is not None: + if isinstance(getattr(self, 'orchestration'), dict): + _dict['orchestration'] = getattr(self, 'orchestration') + else: + _dict['orchestration'] = getattr(self, + 'orchestration').to_dict() if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug - if hasattr(self, 'return_context') and self.return_context is not None: - _dict['return_context'] = self.return_context - if hasattr(self, 'export') and self.export is not None: - _dict['export'] = self.export + 'session_timeout') and self.session_timeout is not None: + _dict['session_timeout'] = self.session_timeout + if hasattr(self, 'integration_references') and getattr( + self, 'integration_references') is not None: + integration_references_list = [] + for v in getattr(self, 'integration_references'): + if isinstance(v, dict): + integration_references_list.append(v) + else: + integration_references_list.append(v.to_dict()) + _dict['integration_references'] = integration_references_list + if hasattr(self, + 'skill_references') and self.skill_references is not None: + skill_references_list = [] + for v in self.skill_references: + if isinstance(v, dict): + skill_references_list.append(v) + else: + skill_references_list.append(v.to_dict()) + _dict['skill_references'] = skill_references_list + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -3082,86 +3639,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptions object.""" + """Return a `str` version of this Environment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptions') -> bool: + def __eq__(self, other: 'Environment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputOptions') -> bool: + def __ne__(self, other: 'Environment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptionsSpelling(): +class EnvironmentCollection(): """ - Spelling correction options for the message. Any options specified on an individual - message override the settings configured for the skill. + EnvironmentCollection. - :attr bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** is - `true`, any spelling corrections are automatically applied to the user input. If - **auto_correct** is `false`, any suggested corrections are returned in the - **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property in - the workspace settings for the skill. - :attr bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned in - the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the workspace - settings for the skill. + :attr List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, - *, - suggestions: bool = None, - auto_correct: bool = None) -> None: + def __init__(self, environments: List['Environment'], + pagination: 'Pagination') -> None: """ - Initialize a MessageInputOptionsSpelling object. + Initialize a EnvironmentCollection object. - :param bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** - is `true`, any spelling corrections are automatically applied to the user - input. If **auto_correct** is `false`, any suggested corrections are - returned in the **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property - in the workspace settings for the skill. - :param bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned - in the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the - workspace settings for the skill. + :param List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.suggestions = suggestions - self.auto_correct = auto_correct + self.environments = environments + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': + """Initialize a EnvironmentCollection object from a json dictionary.""" args = {} - if 'suggestions' in _dict: - args['suggestions'] = _dict.get('suggestions') - if 'auto_correct' in _dict: - args['auto_correct'] = _dict.get('auto_correct') + if 'environments' in _dict: + args['environments'] = [ + Environment.from_dict(v) for v in _dict.get('environments') + ] + else: + raise ValueError( + 'Required property \'environments\' not present in EnvironmentCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in EnvironmentCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + """Initialize a EnvironmentCollection object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = self.suggestions - if hasattr(self, 'auto_correct') and self.auto_correct is not None: - _dict['auto_correct'] = self.auto_correct + if hasattr(self, 'environments') and self.environments is not None: + environments_list = [] + for v in self.environments: + if isinstance(v, dict): + environments_list.append(v) + else: + environments_list.append(v.to_dict()) + _dict['environments'] = environments_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -3169,95 +3724,72 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsSpelling object.""" + """Return a `str` version of this EnvironmentCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: + def __eq__(self, other: 'EnvironmentCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: + def __ne__(self, other: 'EnvironmentCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptionsStateless(): +class EnvironmentReference(): """ - Optional properties that control how the assistant responds. + EnvironmentReference. - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :attr str name: (optional) The name of the environment. + :attr str environment_id: (optional) The unique identifier of the environment. + :attr str environment: (optional) The type of the environment. All environments + other than the draft and live environments have the type `staging`. """ def __init__(self, *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None) -> None: + name: str = None, + environment_id: str = None, + environment: str = None) -> None: """ - Initialize a MessageInputOptionsStateless object. + Initialize a EnvironmentReference object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param str name: (optional) The name of the environment. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug + self.name = name + self.environment_id = environment_id + self.environment = environment @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentReference': + """Initialize a EnvironmentReference object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'environment' in _dict: + args['environment'] = _dict.get('environment') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + """Initialize a EnvironmentReference object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') return _dict def _to_dict(self): @@ -3265,141 +3797,111 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsStateless object.""" + """Return a `str` version of this EnvironmentReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: + def __eq__(self, other: 'EnvironmentReference') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputOptionsStateless') -> bool: + def __ne__(self, other: 'EnvironmentReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class EnvironmentEnum(str, Enum): + """ + The type of the environment. All environments other than the draft and live + environments have the type `staging`. + """ + DRAFT = 'draft' + LIVE = 'live' + STAGING = 'staging' + -class MessageInputStateless(): +class EnvironmentSkill(): """ - An input object that includes the input text. + EnvironmentSkill. - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be sent - to external services by webhooks. - :attr MessageInputOptionsStateless options: (optional) Optional properties that - control how the assistant responds. + :attr str skill_id: The skill ID of the skill. + :attr str type: (optional) The type of the skill. + :attr bool disabled: (optional) Whether the skill is disabled. A disabled skill + in the draft environment does not handle any messages at run time, and it is not + included in saved releases. + :attr str snapshot: (optional) The name of the skill snapshot that is deployed + to the environment (for example, `draft` or `1`). + :attr str skill_reference: (optional) The type of skill identified by the skill + reference. The possible values are `main skill` (for a dialog skill), `actions + skill`, and `search skill`. """ def __init__(self, + skill_id: str, *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptionsStateless' = None) -> None: + type: str = None, + disabled: bool = None, + snapshot: str = None, + skill_reference: str = None) -> None: + """ + Initialize a EnvironmentSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param bool disabled: (optional) Whether the skill is disabled. A disabled + skill in the draft environment does not handle any messages at run time, + and it is not included in saved releases. + :param str snapshot: (optional) The name of the skill snapshot that is + deployed to the environment (for example, `draft` or `1`). + :param str skill_reference: (optional) The type of skill identified by the + skill reference. The possible values are `main skill` (for a dialog skill), + `actions skill`, and `search skill`. """ - Initialize a MessageInputStateless object. - - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be - sent to external services by webhooks. - :param MessageInputOptionsStateless options: (optional) Optional properties - that control how the assistant responds. - """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.options = options + self.skill_id = skill_id + self.type = type + self.disabled = disabled + self.snapshot = snapshot + self.skill_reference = skill_reference @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': - """Initialize a MessageInputStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentSkill': + """Initialize a EnvironmentSkill object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(x) - for x in _dict.get('attachments') - ] - if 'options' in _dict: - args['options'] = MessageInputOptionsStateless.from_dict( - _dict.get('options')) + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in EnvironmentSkill JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'disabled' in _dict: + args['disabled'] = _dict.get('disabled') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + if 'skill_reference' in _dict: + args['skill_reference'] = _dict.get('skill_reference') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputStateless object from a json dictionary.""" + """Initialize a EnvironmentSkill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - _dict['attachments'] = [x.to_dict() for x in self.attachments] - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'disabled') and self.disabled is not None: + _dict['disabled'] = self.disabled + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'skill_reference') and self.skill_reference is not None: + _dict['skill_reference'] = self.skill_reference return _dict def _to_dict(self): @@ -3407,144 +3909,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputStateless object.""" + """Return a `str` version of this EnvironmentSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputStateless') -> bool: + def __eq__(self, other: 'EnvironmentSkill') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageInputStateless') -> bool: + def __ne__(self, other: 'EnvironmentSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): + class TypeEnum(str, Enum): """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. + The type of the skill. """ - TEXT = 'text' + DIALOG = 'dialog' + ACTION = 'action' SEARCH = 'search' -class MessageOutput(): +class IntegrationReference(): """ - Assistant output to be rendered or processed by the client. + IntegrationReference. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :attr MessageOutputDebug debug: (optional) Additional detailed information about - a message response and how it was generated. - :attr dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :attr MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :attr str integration_id: (optional) The integration ID of the integration. + :attr str type: (optional) The type of the integration. """ - def __init__(self, - *, - generic: List['RuntimeResponseGeneric'] = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - actions: List['DialogNodeAction'] = None, - debug: 'MessageOutputDebug' = None, - user_defined: dict = None, - spelling: 'MessageOutputSpelling' = None) -> None: + def __init__(self, *, integration_id: str = None, type: str = None) -> None: """ - Initialize a MessageOutput object. + Initialize a IntegrationReference object. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :param str integration_id: (optional) The integration ID of the + integration. + :param str type: (optional) The type of the integration. """ - self.generic = generic - self.intents = intents - self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + self.integration_id = integration_id + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutput': - """Initialize a MessageOutput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'IntegrationReference': + """Initialize a IntegrationReference object from a json dictionary.""" args = {} - if 'generic' in _dict: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(x) - for x in _dict.get('generic') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') - ] - if 'debug' in _dict: - args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'spelling' in _dict: - args['spelling'] = MessageOutputSpelling.from_dict( - _dict.get('spelling')) + if 'integration_id' in _dict: + args['integration_id'] = _dict.get('integration_id') + if 'type' in _dict: + args['type'] = _dict.get('type') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutput object from a json dictionary.""" + """Initialize a IntegrationReference object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x.to_dict() for x in self.actions] - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'integration_id') and self.integration_id is not None: + _dict['integration_id'] = self.integration_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -3552,97 +3979,189 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutput object.""" + """Return a `str` version of this IntegrationReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutput') -> bool: + def __eq__(self, other: 'IntegrationReference') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageOutput') -> bool: + def __ne__(self, other: 'IntegrationReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebug(): +class Log(): """ - Additional detailed information about a message response and how it was generated. + Log. - :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about dialog nodes that were - triggered during processing of the input message. - :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :attr bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. + :attr str log_id: A unique identifier for the logged event. + :attr MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :attr MessageResponse response: A response from the Watson Assistant service. + :attr str assistant_id: Unique identifier of the assistant. + :attr str session_id: The ID of the session the message was part of. + :attr str skill_id: The unique identifier of the skill that responded to the + message. + :attr str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :attr str request_timestamp: The timestamp for receipt of the message. + :attr str response_timestamp: The timestamp for the system response to the + message. + :attr str language: The language of the assistant to which the message request + was made. + :attr str customer_id: (optional) The customer ID specified for the message, if + any. """ def __init__(self, + log_id: str, + request: 'MessageRequest', + response: 'MessageResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, *, - nodes_visited: List['DialogNodeVisited'] = None, - log_messages: List['DialogLogMessage'] = None, - branch_exited: bool = None, - branch_exited_reason: str = None) -> None: + customer_id: str = None) -> None: """ - Initialize a MessageOutputDebug object. + Initialize a Log object. - :param List[DialogNodeVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about dialog nodes that - were triggered during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the - dialog completed by itself or got interrupted. + :param str log_id: A unique identifier for the logged event. + :param MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :param MessageResponse response: A response from the Watson Assistant + service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to + the message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message + request was made. + :param str customer_id: (optional) The customer ID specified for the + message, if any. """ - self.nodes_visited = nodes_visited - self.log_messages = log_messages - self.branch_exited = branch_exited - self.branch_exited_reason = branch_exited_reason + self.log_id = log_id + self.request = request + self.response = response + self.assistant_id = assistant_id + self.session_id = session_id + self.skill_id = skill_id + self.snapshot = snapshot + self.request_timestamp = request_timestamp + self.response_timestamp = response_timestamp + self.language = language + self.customer_id = customer_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': - """Initialize a MessageOutputDebug object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Log': + """Initialize a Log object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = [ - DialogNodeVisited.from_dict(x) - for x in _dict.get('nodes_visited') - ] - if 'log_messages' in _dict: - args['log_messages'] = [ - DialogLogMessage.from_dict(x) for x in _dict.get('log_messages') - ] - if 'branch_exited' in _dict: - args['branch_exited'] = _dict.get('branch_exited') - if 'branch_exited_reason' in _dict: - args['branch_exited_reason'] = _dict.get('branch_exited_reason') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageOutputDebug object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: + if 'log_id' in _dict: + args['log_id'] = _dict.get('log_id') + else: + raise ValueError( + 'Required property \'log_id\' not present in Log JSON') + if 'request' in _dict: + args['request'] = MessageRequest.from_dict(_dict.get('request')) + else: + raise ValueError( + 'Required property \'request\' not present in Log JSON') + if 'response' in _dict: + args['response'] = MessageResponse.from_dict(_dict.get('response')) + else: + raise ValueError( + 'Required property \'response\' not present in Log JSON') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + else: + raise ValueError( + 'Required property \'assistant_id\' not present in Log JSON') + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') + else: + raise ValueError( + 'Required property \'session_id\' not present in Log JSON') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in Log JSON') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + else: + raise ValueError( + 'Required property \'snapshot\' not present in Log JSON') + if 'request_timestamp' in _dict: + args['request_timestamp'] = _dict.get('request_timestamp') + else: + raise ValueError( + 'Required property \'request_timestamp\' not present in Log JSON' + ) + if 'response_timestamp' in _dict: + args['response_timestamp'] = _dict.get('response_timestamp') + else: + raise ValueError( + 'Required property \'response_timestamp\' not present in Log JSON' + ) + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in Log JSON') + if 'customer_id' in _dict: + args['customer_id'] = _dict.get('customer_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Log object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: - _dict['nodes_visited'] = [x.to_dict() for x in self.nodes_visited] - if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x.to_dict() for x in self.log_messages] - if hasattr(self, 'branch_exited') and self.branch_exited is not None: - _dict['branch_exited'] = self.branch_exited - if hasattr(self, 'branch_exited_reason' - ) and self.branch_exited_reason is not None: - _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'log_id') and self.log_id is not None: + _dict['log_id'] = self.log_id + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() + if hasattr(self, 'assistant_id') and self.assistant_id is not None: + _dict['assistant_id'] = self.assistant_id + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'request_timestamp') and self.request_timestamp is not None: + _dict['request_timestamp'] = self.request_timestamp + if hasattr( + self, + 'response_timestamp') and self.response_timestamp is not None: + _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'customer_id') and self.customer_id is not None: + _dict['customer_id'] = self.customer_id return _dict def _to_dict(self): @@ -3650,90 +4169,80 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebug object.""" + """Return a `str` version of this Log object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputDebug') -> bool: + def __eq__(self, other: 'Log') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageOutputDebug') -> bool: + def __ne__(self, other: 'Log') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BranchExitedReasonEnum(str, Enum): - """ - When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` - specifies whether the dialog completed by itself or got interrupted. - """ - COMPLETED = 'completed' - FALLBACK = 'fallback' - -class MessageOutputSpelling(): +class LogCollection(): """ - Properties describing any spelling corrections in the user input that was received. + LogCollection. - :attr str text: (optional) The user input text that was used to generate the - response. If spelling autocorrection is enabled, this text reflects any spelling - corrections that were applied. - :attr str original_text: (optional) The original user input text. This property - is returned only if autocorrection is enabled and the user input was corrected. - :attr str suggested_text: (optional) Any suggested corrections of the input - text. This property is returned only if spelling correction is enabled and - autocorrection is disabled. + :attr List[Log] logs: An array of objects describing log events. + :attr LogPagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, - *, - text: str = None, - original_text: str = None, - suggested_text: str = None) -> None: + def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: """ - Initialize a MessageOutputSpelling object. + Initialize a LogCollection object. - :param str text: (optional) The user input text that was used to generate - the response. If spelling autocorrection is enabled, this text reflects any - spelling corrections that were applied. - :param str original_text: (optional) The original user input text. This - property is returned only if autocorrection is enabled and the user input - was corrected. - :param str suggested_text: (optional) Any suggested corrections of the - input text. This property is returned only if spelling correction is - enabled and autocorrection is disabled. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned + objects. For more information about using pagination, see + [Pagination](#pagination). """ - self.text = text - self.original_text = original_text - self.suggested_text = suggested_text + self.logs = logs + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': - """Initialize a MessageOutputSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogCollection': + """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') + if 'logs' in _dict: + args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] + else: + raise ValueError( + 'Required property \'logs\' not present in LogCollection JSON') + if 'pagination' in _dict: + args['pagination'] = LogPagination.from_dict( + _dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in LogCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputSpelling object from a json dictionary.""" + """Initialize a LogCollection object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'original_text') and self.original_text is not None: - _dict['original_text'] = self.original_text - if hasattr(self, 'suggested_text') and self.suggested_text is not None: - _dict['suggested_text'] = self.suggested_text + if hasattr(self, 'logs') and self.logs is not None: + logs_list = [] + for v in self.logs: + if isinstance(v, dict): + logs_list.append(v) + else: + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -3741,209 +4250,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputSpelling object.""" + """Return a `str` version of this LogCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputSpelling') -> bool: + def __eq__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageOutputSpelling') -> bool: + def __ne__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageRequest(): +class LogMessageSource(): """ - A stateful message request formatted for the Watson Assistant service. + An object that identifies the dialog element that generated the error message. - :attr MessageInput input: (optional) An input object that includes the input - text. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to set or modify context variables, which can also be - accessed by dialog nodes. The context is stored by the assistant on a - per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. If **user_id** is specified in both locations, the value - specified at the root is used. """ - def __init__(self, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None) -> None: + def __init__(self) -> None: """ - Initialize a MessageRequest object. + Initialize a LogMessageSource object. - :param MessageInput input: (optional) An input object that includes the - input text. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to set or modify context variables, - which can also be accessed by dialog nodes. The context is stored by the - assistant on a per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. If **user_id** is specified in both locations, the - value specified at the root is used. """ - self.input = input - self.context = context - self.user_id = user_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageRequest': - """Initialize a MessageRequest object from a json dictionary.""" - args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - return cls(**args) + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageRequest object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MessageRequest object.""" - return json.dumps(self.to_dict(), indent=2) + def from_dict(cls, _dict: Dict) -> 'LogMessageSource': + """Initialize a LogMessageSource object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) - def __eq__(self, other: 'MessageRequest') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a LogMessageSource object from a json dictionary.""" + return cls.from_dict(_dict) - def __ne__(self, other: 'MessageRequest') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['dialog_node'] = 'LogMessageSourceDialogNode' + mapping['action'] = 'LogMessageSourceAction' + mapping['step'] = 'LogMessageSourceStep' + mapping['handler'] = 'LogMessageSourceHandler' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in LogMessageSource JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) -class MessageResponse(): +class LogPagination(): """ - A response from the Watson Assistant service. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :attr str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :attr str 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, - output: 'MessageOutput', - user_id: str, *, - context: 'MessageContext' = None) -> None: + next_url: str = None, + matched: int = None, + next_cursor: str = None) -> None: """ - Initialize a MessageResponse object. + Initialize a LogPagination object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. + :param str 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.output = output - self.context = context - self.user_id = user_id + self.next_url = next_url + self.matched = matched + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponse': - """Initialize a MessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogPagination': + """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponse JSON' - ) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - else: - raise ValueError( - 'Required property \'user_id\' not present in MessageResponse JSON' - ) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponse object from a json dictionary.""" + """Initialize a LogPagination object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor return _dict def _to_dict(self): @@ -3951,104 +4386,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponse object.""" + """Return a `str` version of this LogPagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponse') -> bool: + def __eq__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageResponse') -> bool: + def __ne__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageResponseStateless(): +class MessageContext(): """ - A stateless response from the Watson Assistant service. + MessageContext. - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContextStateless context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :attr MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the assistant. + :attr MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :attr dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ def __init__(self, - output: 'MessageOutput', - context: 'MessageContextStateless', *, - user_id: str = None) -> None: + global_: 'MessageContextGlobal' = None, + skills: 'MessageContextSkills' = None, + integrations: dict = None) -> None: """ - Initialize a MessageResponseStateless object. + Initialize a MessageContext object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param MessageContextStateless context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.output = output - self.context = context - self.user_id = user_id + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': - """Initialize a MessageResponseStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContext': + """Initialize a MessageContext object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponseStateless JSON' - ) - if 'context' in _dict: - args['context'] = MessageContextStateless.from_dict( - _dict.get('context')) - else: - raise ValueError( - 'Required property \'context\' not present in MessageResponseStateless JSON' - ) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if 'global' in _dict: + args['global_'] = MessageContextGlobal.from_dict( + _dict.get('global')) + if 'skills' in _dict: + args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponseStateless object from a json dictionary.""" + """Initialize a MessageContext object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -4056,54 +4473,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponseStateless object.""" + """Return a `str` version of this MessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponseStateless') -> bool: + def __eq__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'MessageResponseStateless') -> bool: + def __ne__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ResponseGenericChannel(): +class MessageContextGlobal(): """ - ResponseGenericChannel. + Session context data that is shared by all skills used by the assistant. - :attr str channel: (optional) A channel for which the response is intended. + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :attr str session_id: (optional) The session ID. """ - def __init__(self, *, channel: str = None) -> None: + def __init__(self, + *, + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a MessageContextGlobal object. - :param str channel: (optional) A channel for which the response is - intended. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. """ - self.channel = channel + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': + """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if 'system' in _dict: + args['system'] = MessageContextGlobalSystem.from_dict( + _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a MessageContextGlobal object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'channel') and self.channel is not None: - _dict['channel'] = self.channel + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') return _dict def _to_dict(self): @@ -4111,161 +4543,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ResponseGenericChannel object.""" + """Return a `str` version of this MessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ResponseGenericChannel') -> bool: + def __eq__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ResponseGenericChannel') -> bool: + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntity(): +class MessageContextGlobalStateless(): """ - The entity value that was recognized in the user input. + Session context data that is shared by all skills used by the assistant. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :attr str value: The term in the input text that was recognized as an entity - value. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized entity. - :attr List[CaptureGroup] groups: (optional) The recognized capture groups for - the entity, as defined by the entity pattern. - :attr RuntimeEntityInterpretation interpretation: (optional) An object - containing detailed information about the entity recognized in the user input. - This property is included only if the new system entities are enabled for the - skill. - For more information about how the new system entities are interpreted, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). - :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of - possible alternative values that the user might have intended instead of the - value returned in the **value** property. This property is returned only for - `@sys-time` and `@sys-date` entities when the user's input is ambiguous. - This property is included only if the new system entities are enabled for the - skill. - :attr RuntimeEntityRole role: (optional) An object describing the role played by - a system entity that is specifies the beginning or end of a range recognized in - the user input. This property is included only if the new system entities are - enabled for the skill. + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :attr str session_id: (optional) The unique identifier of the session. """ def __init__(self, - entity: str, - value: str, *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None) -> None: + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: """ - Initialize a RuntimeEntity object. + Initialize a MessageContextGlobalStateless object. - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. - :param List[CaptureGroup] groups: (optional) The recognized capture groups - for the entity, as defined by the entity pattern. - :param RuntimeEntityInterpretation interpretation: (optional) An object - containing detailed information about the entity recognized in the user - input. This property is included only if the new system entities are - enabled for the skill. - For more information about how the new system entities are interpreted, see - the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). - :param List[RuntimeEntityAlternative] alternatives: (optional) An array of - possible alternative values that the user might have intended instead of - the value returned in the **value** property. This property is returned - only for `@sys-time` and `@sys-date` entities when the user's input is - ambiguous. - This property is included only if the new system entities are enabled for - the skill. - :param RuntimeEntityRole role: (optional) An object describing the role - played by a system entity that is specifies the beginning or end of a range - recognized in the user input. This property is included only if the new - system entities are enabled for the skill. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ - self.entity = entity - self.location = location - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': + """Initialize a MessageContextGlobalStateless object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') - else: - raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' - ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') - else: - raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(x) for x in _dict.get('groups') - ] - if 'interpretation' in _dict: - args['interpretation'] = RuntimeEntityInterpretation.from_dict( - _dict.get('interpretation')) - if 'alternatives' in _dict: - args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(x) - for x in _dict.get('alternatives') - ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) + if 'system' in _dict: + args['system'] = MessageContextGlobalSystem.from_dict( + _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a MessageContextGlobalStateless object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'entity') and self.entity is not None: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x.to_dict() for x in self.groups] - if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] - if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role.to_dict() + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -4273,64 +4613,194 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this MessageContextGlobalStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntity') -> bool: + def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative(): +class MessageContextGlobalSystem(): """ - An alternative value for the recognized entity. + Built-in system properties that apply to all skills used by the assistant. - :attr str value: (optional) The entity value that was recognized in the user - input. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized entity. + :attr str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. + :attr int turn_count: (optional) A counter that is automatically incremented + with each turn of the conversation. A value of 1 indicates that this is the the + first turn of a new conversation, which can affect the behavior of some skills + (for example, triggering the start node of a dialog). + :attr str locale: (optional) The language code for localization in the user + input. The specified locale overrides the default for the assistant, and is used + for interpreting entity values in user input such as date values. For example, + `04/03/2018` might be interpreted either as April 3 or March 4, depending on the + locale. + This property is included only if the new system entities are enabled for the + skill. + :attr str reference_time: (optional) The base time for interpreting any relative + time mentions in the user input. The specified time overrides the current server + time, and is used to calculate times mentioned in relative terms such as `now` + or `tomorrow`. This can be useful for simulating past or future times for + testing purposes, or when analyzing documents such as news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for the + skill. + :attr str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :attr str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). + :attr bool skip_user_input: (optional) For internal use only. """ - def __init__(self, *, value: str = None, confidence: float = None) -> None: + def __init__(self, + *, + timezone: str = None, + user_id: str = None, + turn_count: int = None, + locale: str = None, + reference_time: str = None, + session_start_time: str = None, + state: str = None, + skip_user_input: bool = None) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a MessageContextGlobalSystem object. - :param str value: (optional) The entity value that was recognized in the - user input. - :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically + incremented with each turn of the conversation. A value of 1 indicates that + this is the the first turn of a new conversation, which can affect the + behavior of some skills (for example, triggering the start node of a + dialog). + :param str locale: (optional) The language code for localization in the + user input. The specified locale overrides the default for the assistant, + and is used for interpreting entity values in user input such as date + values. For example, `04/03/2018` might be interpreted either as April 3 or + March 4, depending on the locale. + This property is included only if the new system entities are enabled for + the skill. + :param str reference_time: (optional) The base time for interpreting any + relative time mentions in the user input. The specified time overrides the + current server time, and is used to calculate times mentioned in relative + terms such as `now` or `tomorrow`. This can be useful for simulating past + or future times for testing purposes, or when analyzing documents such as + news articles. + This value must be a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for + the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ - self.value = value - self.confidence = confidence + self.timezone = timezone + self.user_id = user_id + self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state + self.skip_user_input = skip_user_input @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if 'timezone' in _dict: + args['timezone'] = _dict.get('timezone') + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + if 'turn_count' in _dict: + args['turn_count'] = _dict.get('turn_count') + if 'locale' in _dict: + args['locale'] = _dict.get('locale') + if 'reference_time' in _dict: + args['reference_time'] = _dict.get('reference_time') + if 'session_start_time' in _dict: + args['session_start_time'] = _dict.get('session_start_time') + if 'state' in _dict: + args['state'] = _dict.get('state') + if 'skip_user_input' in _dict: + args['skip_user_input'] = _dict.get('skip_user_input') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, '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, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'turn_count') and self.turn_count is not None: + _dict['turn_count'] = self.turn_count + if hasattr(self, 'locale') and self.locale is not None: + _dict['locale'] = self.locale + if hasattr(self, 'reference_time') and self.reference_time is not None: + _dict['reference_time'] = self.reference_time + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + if hasattr(self, + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input return _dict def _to_dict(self): @@ -4338,138 +4808,3038 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this MessageContextGlobalSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LocaleEnum(str, Enum): + """ + The language code for localization in the user input. The specified locale + overrides the default for the assistant, and is used for interpreting entity + values in user input such as date values. For example, `04/03/2018` might be + interpreted either as April 3 or March 4, depending on the locale. + This property is included only if the new system entities are enabled for the + skill. + """ + EN_US = 'en-us' + EN_CA = 'en-ca' + EN_GB = 'en-gb' + AR_AR = 'ar-ar' + CS_CZ = 'cs-cz' + DE_DE = 'de-de' + ES_ES = 'es-es' + FR_FR = 'fr-fr' + IT_IT = 'it-it' + JA_JP = 'ja-jp' + KO_KR = 'ko-kr' + NL_NL = 'nl-nl' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + -class RuntimeEntityInterpretation(): +class MessageContextSkillAction(): """ - RuntimeEntityInterpretation. + Context variables that are used by the action skill. - :attr str calendar_type: (optional) The calendar used to represent a recognized - date (for example, `Gregorian`). - :attr str datetime_link: (optional) A unique identifier used to associate a - recognized time and date. If the user input contains a date and time that are - mentioned together (for example, `Today at 5`, the same **datetime_link** value - is returned for both the `@sys-date` and `@sys-time` entities). - :attr str festival: (optional) A locale-specific holiday name (such as - `thanksgiving` or `christmas`). This property is included when a `@sys-date` - entity is recognized based on a holiday name in the user input. - :attr str granularity: (optional) The precision or duration of a time range - specified by a recognized `@sys-time` or `@sys-date` entity. - :attr str range_link: (optional) A unique identifier used to associate multiple - recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are - recognized as a range of values in the user's input (for example, `from July 4 - until July 14` or `from 20 to 25`). - :attr str range_modifier: (optional) The word in the user input that indicates - that a `sys-date` or `sys-time` entity is part of an implied range where only - one date or time is specified (for example, `since` or `until`). - :attr float relative_day: (optional) A recognized mention of a relative day, - represented numerically as an offset from the current date (for example, `-1` - for `yesterday` or `10` for `in ten days`). - :attr float relative_month: (optional) A recognized mention of a relative month, - represented numerically as an offset from the current month (for example, `1` - for `next month` or `-3` for `three months ago`). - :attr float relative_week: (optional) A recognized mention of a relative week, - represented numerically as an offset from the current week (for example, `2` for - `in two weeks` or `-1` for `last week). - :attr float relative_weekend: (optional) A recognized mention of a relative date - range for a weekend, represented numerically as an offset from the current - weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). - :attr float relative_year: (optional) A recognized mention of a relative year, - represented numerically as an offset from the current year (for example, `1` for - `next year` or `-5` for `five years ago`). - :attr float specific_day: (optional) A recognized mention of a specific date, - represented numerically as the date within the month (for example, `30` for - `June 30`.). - :attr str specific_day_of_week: (optional) A recognized mention of a specific - day of the week as a lowercase string (for example, `monday`). - :attr float specific_month: (optional) A recognized mention of a specific month, - represented numerically (for example, `7` for `July`). - :attr float specific_quarter: (optional) A recognized mention of a specific - quarter, represented numerically (for example, `3` for `the third quarter`). - :attr float specific_year: (optional) A recognized mention of a specific year - (for example, `2016`). - :attr float numeric_value: (optional) A recognized numeric value, represented as - an integer or double. - :attr str subtype: (optional) The type of numeric value recognized in the user - input (`integer` or `rational`). - :attr str part_of_day: (optional) A recognized term for a time that was - mentioned as a part of the day in the user's input (for example, `morning` or - `afternoon`). - :attr float relative_hour: (optional) A recognized mention of a relative hour, - represented numerically as an offset from the current hour (for example, `3` for - `in three hours` or `-1` for `an hour ago`). - :attr float relative_minute: (optional) A recognized mention of a relative time, - represented numerically as an offset in minutes from the current time (for - example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). - :attr float relative_second: (optional) A recognized mention of a relative time, - represented numerically as an offset in seconds from the current time (for - example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :attr float specific_hour: (optional) A recognized specific hour mentioned as - part of a time value (for example, `10` for `10:15 AM`.). - :attr float specific_minute: (optional) A recognized specific minute mentioned - as part of a time value (for example, `15` for `10:15 AM`.). - :attr float specific_second: (optional) A recognized specific second mentioned - as part of a time value (for example, `30` for `10:15:30 AM`.). - :attr str timezone: (optional) A recognized time zone mentioned as part of a - time value (for example, `EST`). + :attr dict user_defined: (optional) An object containing any arbitrary variables + that can be read and written by a particular skill. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. + :attr dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :attr dict skill_variables: (optional) An object containing skill variables. (In + the Watson Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. """ def __init__(self, *, - calendar_type: str = None, - datetime_link: str = None, - festival: str = None, - granularity: str = None, - range_link: str = None, - range_modifier: str = None, - relative_day: float = None, - relative_month: float = None, - relative_week: float = None, - relative_weekend: float = None, - relative_year: float = None, - specific_day: float = None, - specific_day_of_week: str = None, - specific_month: float = None, - specific_quarter: float = None, - specific_year: float = None, - numeric_value: float = None, - subtype: str = None, - part_of_day: str = None, - relative_hour: float = None, - relative_minute: float = None, - relative_second: float = None, - specific_hour: float = None, - specific_minute: float = None, - specific_second: float = None, - timezone: str = None) -> None: + user_defined: dict = None, + system: 'MessageContextSkillSystem' = None, + action_variables: dict = None, + skill_variables: dict = None) -> None: """ - Initialize a RuntimeEntityInterpretation object. + Initialize a MessageContextSkillAction object. - :param str calendar_type: (optional) The calendar used to represent a - recognized date (for example, `Gregorian`). - :param str datetime_link: (optional) A unique identifier used to associate - a recognized time and date. If the user input contains a date and time that - are mentioned together (for example, `Today at 5`, the same - **datetime_link** value is returned for both the `@sys-date` and - `@sys-time` entities). - :param str festival: (optional) A locale-specific holiday name (such as - `thanksgiving` or `christmas`). This property is included when a - `@sys-date` entity is recognized based on a holiday name in the user input. - :param str granularity: (optional) The precision or duration of a time - range specified by a recognized `@sys-time` or `@sys-date` entity. - :param str range_link: (optional) A unique identifier used to associate + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the Watson Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + """ + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillAction': + """Initialize a MessageContextSkillAction object from a json dictionary.""" + args = {} + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'system' in _dict: + args['system'] = MessageContextSkillSystem.from_dict( + _dict.get('system')) + if 'action_variables' in _dict: + args['action_variables'] = _dict.get('action_variables') + if 'skill_variables' in _dict: + args['skill_variables'] = _dict.get('skill_variables') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillAction object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillAction') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextSkillAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextSkillDialog(): + """ + Context variables that are used by the dialog skill. + + :attr dict user_defined: (optional) An object containing any arbitrary variables + that can be read and written by a particular skill. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. + """ + + def __init__(self, + *, + user_defined: dict = None, + system: 'MessageContextSkillSystem' = None) -> None: + """ + Initialize a MessageContextSkillDialog object. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + """ + self.user_defined = user_defined + self.system = system + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillDialog': + """Initialize a MessageContextSkillDialog object from a json dictionary.""" + args = {} + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'system' in _dict: + args['system'] = MessageContextSkillSystem.from_dict( + _dict.get('system')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillDialog object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillDialog object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillDialog') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextSkillDialog') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextSkillSystem(): + """ + System context data used by the skill. + + :attr str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + """ + + # The set of defined properties for the class + _properties = frozenset(['state']) + + def __init__(self, *, state: str = None, **kwargs) -> None: + """ + Initialize a MessageContextSkillSystem object. + + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + :param **kwargs: (optional) Any additional properties. + """ + self.state = state + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" + args = {} + if 'state' in _dict: + args['state'] = _dict.get('state') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillSystem object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in MessageContextSkillSystem._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillSystem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextSkills(): + """ + Context data specific to particular skills used by the assistant. + + :attr MessageContextSkillDialog main_skill: (optional) Context variables that + are used by the dialog skill. + :attr MessageContextSkillAction actions_skill: (optional) Context variables that + are used by the action skill. + """ + + def __init__(self, + *, + main_skill: 'MessageContextSkillDialog' = None, + actions_skill: 'MessageContextSkillAction' = None) -> None: + """ + Initialize a MessageContextSkills object. + + :param MessageContextSkillDialog main_skill: (optional) Context variables + that are used by the dialog skill. + :param MessageContextSkillAction actions_skill: (optional) Context + variables that are used by the action skill. + """ + self.main_skill = main_skill + self.actions_skill = actions_skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': + """Initialize a MessageContextSkills object from a json dictionary.""" + args = {} + if 'main skill' in _dict: + args['main_skill'] = MessageContextSkillDialog.from_dict( + _dict.get('main skill')) + if 'actions skill' in _dict: + args['actions_skill'] = MessageContextSkillAction.from_dict( + _dict.get('actions skill')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkills object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkills object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkills') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextSkills') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextStateless(): + """ + MessageContextStateless. + + :attr MessageContextGlobalStateless global_: (optional) Session context data + that is shared by all skills used by the assistant. + :attr MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :attr dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + + def __init__(self, + *, + global_: 'MessageContextGlobalStateless' = None, + skills: 'MessageContextSkills' = None, + integrations: dict = None) -> None: + """ + Initialize a MessageContextStateless object. + + :param MessageContextGlobalStateless global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + self.global_ = global_ + self.skills = skills + self.integrations = integrations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': + """Initialize a MessageContextStateless object from a json dictionary.""" + args = {} + if 'global' in _dict: + args['global_'] = MessageContextGlobalStateless.from_dict( + _dict.get('global')) + if 'skills' in _dict: + args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextStateless object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageContextStateless object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextStateless') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageContextStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInput(): + """ + An input object that includes the input text. + + :attr str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :attr str suggestion_id: (optional) For internal use only. + :attr List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :attr RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :attr MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. + """ + + def __init__(self, + *, + message_type: str = None, + text: str = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None, + attachments: List['MessageInputAttachment'] = None, + analytics: 'RequestAnalytics' = None, + options: 'MessageInputOptions' = None) -> None: + """ + Initialize a MessageInput object. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInput': + """Initialize a MessageInput object from a json dictionary.""" + args = {} + if 'message_type' in _dict: + args['message_type'] = _dict.get('message_type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'suggestion_id' in _dict: + args['suggestion_id'] = _dict.get('suggestion_id') + if 'attachments' in _dict: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) + for v in _dict.get('attachments') + ] + if 'analytics' in _dict: + args['analytics'] = RequestAnalytics.from_dict( + _dict.get('analytics')) + if 'options' in _dict: + args['options'] = MessageInputOptions.from_dict( + _dict.get('options')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + TEXT = 'text' + SEARCH = 'search' + + +class MessageInputAttachment(): + """ + A reference to a media file to be sent as an attachment with the message. + + :attr str url: The URL of the media file. + :attr str media_type: (optional) The media content type (such as a MIME type) of + the attachment. + """ + + def __init__(self, url: str, *, media_type: str = None) -> None: + """ + Initialize a MessageInputAttachment object. + + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME + type) of the attachment. + """ + self.url = url + self.media_type = media_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': + """Initialize a MessageInputAttachment object from a json dictionary.""" + args = {} + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in MessageInputAttachment JSON' + ) + if 'media_type' in _dict: + args['media_type'] = _dict.get('media_type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputAttachment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'media_type') and self.media_type is not None: + _dict['media_type'] = self.media_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputAttachment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputAttachment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputAttachment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputOptions(): + """ + Optional properties that control how the assistant responds. + + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :attr bool return_context: (optional) Whether to return session context with the + response. If you specify `true`, the response includes the `context` property. + If you also specify **debug**=`true`, the returned skill context includes the + `system.state` property. + :attr bool export: (optional) Whether to return session context, including full + conversation state. If you specify `true`, the response includes the `context` + property, and the skill context includes the `system.state` property. + **Note:** If **export**=`true`, the context is returned regardless of the value + of **return_context**. + """ + + def __init__(self, + *, + restart: bool = None, + alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None, + return_context: bool = None, + export: bool = None) -> None: + """ + Initialize a MessageInputOptions object. + + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :param bool return_context: (optional) Whether to return session context + with the response. If you specify `true`, the response includes the + `context` property. If you also specify **debug**=`true`, the returned + skill context includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including + full conversation state. If you specify `true`, the response includes the + `context` property, and the skill context includes the `system.state` + property. + **Note:** If **export**=`true`, the context is returned regardless of the + value of **return_context**. + """ + self.restart = restart + self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug + self.return_context = return_context + self.export = export + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': + """Initialize a MessageInputOptions object from a json dictionary.""" + args = {} + if 'restart' in _dict: + args['restart'] = _dict.get('restart') + if 'alternate_intents' in _dict: + args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling.from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') + if 'return_context' in _dict: + args['return_context'] = _dict.get('return_context') + if 'export' in _dict: + args['export'] = _dict.get('export') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + if hasattr(self, 'return_context') and self.return_context is not None: + _dict['return_context'] = self.return_context + if hasattr(self, 'export') and self.export is not None: + _dict['export'] = self.export + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputOptions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputOptions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputOptions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputOptionsSpelling(): + """ + Spelling correction options for the message. Any options specified on an individual + message override the settings configured for the skill. + + :attr bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** is + `true`, any spelling corrections are automatically applied to the user input. If + **auto_correct** is `false`, any suggested corrections are returned in the + **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property in + the workspace settings for the skill. + :attr bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned in + the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the workspace + settings for the skill. + """ + + def __init__(self, + *, + suggestions: bool = None, + auto_correct: bool = None) -> None: + """ + Initialize a MessageInputOptionsSpelling object. + + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** + is `true`, any spelling corrections are automatically applied to the user + input. If **auto_correct** is `false`, any suggested corrections are + returned in the **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property + in the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned + in the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the + workspace settings for the skill. + """ + self.suggestions = suggestions + self.auto_correct = auto_correct + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + args = {} + if 'suggestions' in _dict: + args['suggestions'] = _dict.get('suggestions') + if 'auto_correct' in _dict: + args['auto_correct'] = _dict.get('auto_correct') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = self.suggestions + if hasattr(self, 'auto_correct') and self.auto_correct is not None: + _dict['auto_correct'] = self.auto_correct + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputOptionsSpelling object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputOptionsStateless(): + """ + Optional properties that control how the assistant responds. + + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + + def __init__(self, + *, + restart: bool = None, + alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None) -> None: + """ + Initialize a MessageInputOptionsStateless object. + + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + self.restart = restart + self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': + """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + args = {} + if 'restart' in _dict: + args['restart'] = _dict.get('restart') + if 'alternate_intents' in _dict: + args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling.from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputOptionsStateless object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputOptionsStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputStateless(): + """ + An input object that includes the input text. + + :attr str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :attr str suggestion_id: (optional) For internal use only. + :attr List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :attr RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :attr MessageInputOptionsStateless options: (optional) Optional properties that + control how the assistant responds. + """ + + def __init__(self, + *, + message_type: str = None, + text: str = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None, + attachments: List['MessageInputAttachment'] = None, + analytics: 'RequestAnalytics' = None, + options: 'MessageInputOptionsStateless' = None) -> None: + """ + Initialize a MessageInputStateless object. + + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptionsStateless options: (optional) Optional properties + that control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': + """Initialize a MessageInputStateless object from a json dictionary.""" + args = {} + if 'message_type' in _dict: + args['message_type'] = _dict.get('message_type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'suggestion_id' in _dict: + args['suggestion_id'] = _dict.get('suggestion_id') + if 'attachments' in _dict: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) + for v in _dict.get('attachments') + ] + if 'analytics' in _dict: + args['analytics'] = RequestAnalytics.from_dict( + _dict.get('analytics')) + if 'options' in _dict: + args['options'] = MessageInputOptionsStateless.from_dict( + _dict.get('options')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputStateless object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageInputStateless object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputStateless') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageInputStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + TEXT = 'text' + SEARCH = 'search' + + +class MessageOutput(): + """ + Assistant output to be rendered or processed by the client. + + :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :attr List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :attr List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :attr MessageOutputDebug debug: (optional) Additional detailed information about + a message response and how it was generated. + :attr dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :attr MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + """ + + def __init__(self, + *, + generic: List['RuntimeResponseGeneric'] = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + actions: List['DialogNodeAction'] = None, + debug: 'MessageOutputDebug' = None, + user_defined: dict = None, + spelling: 'MessageOutputSpelling' = None) -> None: + """ + Initialize a MessageOutput object. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutput': + """Initialize a MessageOutput object from a json dictionary.""" + args = {} + if 'generic' in _dict: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) + for v in _dict.get('generic') + ] + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'actions' in _dict: + args['actions'] = [ + DialogNodeAction.from_dict(v) for v in _dict.get('actions') + ] + if 'debug' in _dict: + args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'spelling' in _dict: + args['spelling'] = MessageOutputSpelling.from_dict( + _dict.get('spelling')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutput object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageOutput object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutput') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageOutput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageOutputDebug(): + """ + Additional detailed information about a message response and how it was generated. + + :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were visited + during processing of the input message. + :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :attr bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` + by the assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. + :attr List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + objects containing detailed diagnostic information about dialog nodes and + actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. + """ + + def __init__( + self, + *, + nodes_visited: List['DialogNodeVisited'] = None, + log_messages: List['DialogLogMessage'] = None, + branch_exited: bool = None, + branch_exited_reason: str = None, + turn_events: List['MessageOutputDebugTurnEvent'] = None) -> None: + """ + Initialize a MessageOutputDebug object. + + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that + were visited during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array + of objects containing detailed diagnostic information about dialog nodes + and actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. + """ + self.nodes_visited = nodes_visited + self.log_messages = log_messages + self.branch_exited = branch_exited + self.branch_exited_reason = branch_exited_reason + self.turn_events = turn_events + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': + """Initialize a MessageOutputDebug object from a json dictionary.""" + args = {} + if 'nodes_visited' in _dict: + args['nodes_visited'] = [ + DialogNodeVisited.from_dict(v) + for v in _dict.get('nodes_visited') + ] + if 'log_messages' in _dict: + args['log_messages'] = [ + DialogLogMessage.from_dict(v) for v in _dict.get('log_messages') + ] + if 'branch_exited' in _dict: + args['branch_exited'] = _dict.get('branch_exited') + if 'branch_exited_reason' in _dict: + args['branch_exited_reason'] = _dict.get('branch_exited_reason') + if 'turn_events' in _dict: + args['turn_events'] = [ + MessageOutputDebugTurnEvent.from_dict(v) + for v in _dict.get('turn_events') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputDebug object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + nodes_visited_list = [] + for v in self.nodes_visited: + if isinstance(v, dict): + nodes_visited_list.append(v) + else: + nodes_visited_list.append(v.to_dict()) + _dict['nodes_visited'] = nodes_visited_list + if hasattr(self, 'log_messages') and self.log_messages is not None: + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list + if hasattr(self, 'branch_exited') and self.branch_exited is not None: + _dict['branch_exited'] = self.branch_exited + if hasattr(self, 'branch_exited_reason' + ) and self.branch_exited_reason is not None: + _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'turn_events') and self.turn_events is not None: + turn_events_list = [] + for v in self.turn_events: + if isinstance(v, dict): + turn_events_list.append(v) + else: + turn_events_list.append(v.to_dict()) + _dict['turn_events'] = turn_events_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageOutputDebug object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutputDebug') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageOutputDebug') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class BranchExitedReasonEnum(str, Enum): + """ + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. + """ + COMPLETED = 'completed' + FALLBACK = 'fallback' + + +class MessageOutputDebugTurnEvent(): + """ + MessageOutputDebugTurnEvent. + + """ + + def __init__(self) -> None: + """ + Initialize a MessageOutputDebugTurnEvent object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' + mapping[ + 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' + mapping[ + 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' + mapping[ + 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' + mapping[ + 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' + mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' + mapping[ + 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' + disc_value = _dict.get('event') + if disc_value is None: + raise ValueError( + 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class MessageOutputSpelling(): + """ + Properties describing any spelling corrections in the user input that was received. + + :attr str text: (optional) The user input text that was used to generate the + response. If spelling autocorrection is enabled, this text reflects any spelling + corrections that were applied. + :attr str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. + :attr str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. + """ + + def __init__(self, + *, + text: str = None, + original_text: str = None, + suggested_text: str = None) -> None: + """ + Initialize a MessageOutputSpelling object. + + :param str text: (optional) The user input text that was used to generate + the response. If spelling autocorrection is enabled, this text reflects any + spelling corrections that were applied. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. + """ + self.text = text + self.original_text = original_text + self.suggested_text = suggested_text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': + """Initialize a MessageOutputSpelling object from a json dictionary.""" + args = {} + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'original_text' in _dict: + args['original_text'] = _dict.get('original_text') + if 'suggested_text' in _dict: + args['suggested_text'] = _dict.get('suggested_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputSpelling object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageOutputSpelling object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutputSpelling') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageOutputSpelling') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageRequest(): + """ + A stateful message request formatted for the Watson Assistant service. + + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. + """ + + def __init__(self, + *, + input: 'MessageInput' = None, + context: 'MessageContext' = None, + user_id: str = None) -> None: + """ + Initialize a MessageRequest object. + + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. + """ + self.input = input + self.context = context + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageRequest': + """Initialize a MessageRequest object from a json dictionary.""" + args = {} + if 'input' in _dict: + args['input'] = MessageInput.from_dict(_dict.get('input')) + if 'context' in _dict: + args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageRequest object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageRequest object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageRequest') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageRequest') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageResponse(): + """ + A response from the Watson Assistant service. + + :attr MessageOutput output: Assistant output to be rendered or processed by the + client. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :attr str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + """ + + def __init__(self, + output: 'MessageOutput', + user_id: str, + *, + context: 'MessageContext' = None) -> None: + """ + Initialize a MessageResponse object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + """ + self.output = output + self.context = context + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageResponse': + """Initialize a MessageResponse object from a json dictionary.""" + args = {} + if 'output' in _dict: + args['output'] = MessageOutput.from_dict(_dict.get('output')) + else: + raise ValueError( + 'Required property \'output\' not present in MessageResponse JSON' + ) + if 'context' in _dict: + args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + else: + raise ValueError( + 'Required property \'user_id\' not present in MessageResponse JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageResponseStateless(): + """ + A stateless response from the Watson Assistant service. + + :attr MessageOutput output: Assistant output to be rendered or processed by the + client. + :attr MessageContextStateless context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + """ + + def __init__(self, + output: 'MessageOutput', + context: 'MessageContextStateless', + *, + user_id: str = None) -> None: + """ + Initialize a MessageResponseStateless object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param MessageContextStateless context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + """ + self.output = output + self.context = context + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': + """Initialize a MessageResponseStateless object from a json dictionary.""" + args = {} + if 'output' in _dict: + args['output'] = MessageOutput.from_dict(_dict.get('output')) + else: + raise ValueError( + 'Required property \'output\' not present in MessageResponseStateless JSON' + ) + if 'context' in _dict: + args['context'] = MessageContextStateless.from_dict( + _dict.get('context')) + else: + raise ValueError( + 'Required property \'context\' not present in MessageResponseStateless JSON' + ) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageResponseStateless object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this MessageResponseStateless object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageResponseStateless') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'MessageResponseStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Pagination(): + """ + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). + + :attr str refresh_url: The URL that will return the same page of results. + :attr str next_url: (optional) The URL that will return the next page of + results. + :attr int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :attr int matched: (optional) Reserved for future use. + :attr str refresh_cursor: (optional) A token identifying the current page of + results. + :attr str next_cursor: (optional) A token identifying the next page of results. + """ + + def __init__(self, + refresh_url: str, + *, + next_url: str = None, + total: int = None, + matched: int = None, + refresh_cursor: str = None, + next_cursor: str = None) -> None: + """ + Initialize a Pagination object. + + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. + """ + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" + args = {} + if 'refresh_url' in _dict: + args['refresh_url'] = _dict.get('refresh_url') + else: + raise ValueError( + 'Required property \'refresh_url\' not present in Pagination JSON' + ) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'total' in _dict: + args['total'] = _dict.get('total') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'refresh_cursor' in _dict: + args['refresh_cursor'] = _dict.get('refresh_cursor') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Pagination object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Pagination') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Pagination') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Release(): + """ + Release. + + :attr str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :attr str description: (optional) The description of the release. + :attr List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :attr ReleaseContent content: (optional) An object identifying the versionable + content objects (such as skill snapshots) that are included in the release. + :attr str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :attr datetime created: (optional) The timestamp for creation of the object. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. + """ + + def __init__(self, + *, + release: str = None, + description: str = None, + environment_references: List['EnvironmentReference'] = None, + content: 'ReleaseContent' = None, + status: str = None, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Release object. + + :param str description: (optional) The description of the release. + """ + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" + args = {} + if 'release' in _dict: + args['release'] = _dict.get('release') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'environment_references' in _dict: + args['environment_references'] = [ + EnvironmentReference.from_dict(v) + for v in _dict.get('environment_references') + ] + if 'content' in _dict: + args['content'] = ReleaseContent.from_dict(_dict.get('content')) + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Release object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Release object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Release') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Release') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class ReleaseCollection(): + """ + ReleaseCollection. + + :attr List[Release] releases: An array of objects describing the releases + associated with an assistant. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__(self, releases: List['Release'], + pagination: 'Pagination') -> None: + """ + Initialize a ReleaseCollection object. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.releases = releases + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" + args = {} + if 'releases' in _dict: + args['releases'] = [ + Release.from_dict(v) for v in _dict.get('releases') + ] + else: + raise ValueError( + 'Required property \'releases\' not present in ReleaseCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'releases') and self.releases is not None: + releases_list = [] + for v in self.releases: + if isinstance(v, dict): + releases_list.append(v) + else: + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ReleaseCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseContent(): + """ + An object identifying the versionable content objects (such as skill snapshots) that + are included in the release. + + :attr List[ReleaseSkill] skills: (optional) The skill snapshots that are + included in the release. + """ + + def __init__(self, *, skills: List['ReleaseSkill'] = None) -> None: + """ + Initialize a ReleaseContent object. + + """ + self.skills = skills + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" + args = {} + if 'skills' in _dict: + args['skills'] = [ + ReleaseSkill.from_dict(v) for v in _dict.get('skills') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseContent object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skills') and getattr(self, 'skills') is not None: + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ReleaseContent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseContent') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseContent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseSkill(): + """ + ReleaseSkill. + + :attr str skill_id: The skill ID of the skill. + :attr str type: (optional) The type of the skill. + :attr str snapshot: (optional) The name of the skill snapshot that is saved as + part of the release (for example, `draft` or `1`). + """ + + def __init__(self, + skill_id: str, + *, + type: str = None, + snapshot: str = None) -> None: + """ + Initialize a ReleaseSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is + saved as part of the release (for example, `draft` or `1`). + """ + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': + """Initialize a ReleaseSkill object from a json dictionary.""" + args = {} + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in ReleaseSkill JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ReleaseSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class RequestAnalytics(): + """ + An optional object containing analytics data. Currently, this data is used only for + events sent to the Segment extension. + + :attr str browser: (optional) The browser that was used to send the message that + triggered the event. + :attr str device: (optional) The type of device that was used to send the + message that triggered the event. + :attr str page_url: (optional) The URL of the web page that was used to send the + message that triggered the event. + """ + + def __init__(self, + *, + browser: str = None, + device: str = None, + page_url: str = None) -> None: + """ + Initialize a RequestAnalytics object. + + :param str browser: (optional) The browser that was used to send the + message that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to + send the message that triggered the event. + """ + self.browser = browser + self.device = device + self.page_url = page_url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': + """Initialize a RequestAnalytics object from a json dictionary.""" + args = {} + if 'browser' in _dict: + args['browser'] = _dict.get('browser') + if 'device' in _dict: + args['device'] = _dict.get('device') + if 'pageUrl' in _dict: + args['page_url'] = _dict.get('pageUrl') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RequestAnalytics object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'browser') and self.browser is not None: + _dict['browser'] = self.browser + if hasattr(self, 'device') and self.device is not None: + _dict['device'] = self.device + if hasattr(self, 'page_url') and self.page_url is not None: + _dict['pageUrl'] = self.page_url + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RequestAnalytics object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RequestAnalytics') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RequestAnalytics') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericChannel(): + """ + ResponseGenericChannel. + + :attr str channel: (optional) A channel for which the response is intended. + """ + + def __init__(self, *, channel: str = None) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if 'channel' in _dict: + args['channel'] = _dict.get('channel') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntity(): + """ + The entity value that was recognized in the user input. + + :attr str entity: An entity detected in the input. + :attr List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :attr str value: The term in the input text that was recognized as an entity + value. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the recognized entity. + :attr List[CaptureGroup] groups: (optional) The recognized capture groups for + the entity, as defined by the entity pattern. + :attr RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user input. + This property is included only if the new system entities are enabled for the + skill. + For more information about how the new system entities are interpreted, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of the + value returned in the **value** property. This property is returned only for + `@sys-time` and `@sys-date` entities when the user's input is ambiguous. + This property is included only if the new system entities are enabled for the + skill. + :attr RuntimeEntityRole role: (optional) An object describing the role played by + a system entity that is specifies the beginning or end of a range recognized in + the user input. This property is included only if the new system entities are + enabled for the skill. + :attr str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__(self, + entity: str, + value: str, + *, + location: List[int] = None, + confidence: float = None, + groups: List['CaptureGroup'] = None, + interpretation: 'RuntimeEntityInterpretation' = None, + alternatives: List['RuntimeEntityAlternative'] = None, + role: 'RuntimeEntityRole' = None, + skill: str = None) -> None: + """ + Initialize a RuntimeEntity object. + + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized entity. + :param List[CaptureGroup] groups: (optional) The recognized capture groups + for the entity, as defined by the entity pattern. + :param RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user + input. This property is included only if the new system entities are + enabled for the skill. + For more information about how the new system entities are interpreted, see + the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of + the value returned in the **value** property. This property is returned + only for `@sys-time` and `@sys-date` entities when the user's input is + ambiguous. + This property is included only if the new system entities are enabled for + the skill. + :param RuntimeEntityRole role: (optional) An object describing the role + played by a system entity that is specifies the beginning or end of a range + recognized in the user input. This property is included only if the new + system entities are enabled for the skill. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" + args = {} + if 'entity' in _dict: + args['entity'] = _dict.get('entity') + else: + raise ValueError( + 'Required property \'entity\' not present in RuntimeEntity JSON' + ) + if 'location' in _dict: + args['location'] = _dict.get('location') + if 'value' in _dict: + args['value'] = _dict.get('value') + else: + raise ValueError( + 'Required property \'value\' not present in RuntimeEntity JSON') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'groups' in _dict: + args['groups'] = [ + CaptureGroup.from_dict(v) for v in _dict.get('groups') + ] + if 'interpretation' in _dict: + args['interpretation'] = RuntimeEntityInterpretation.from_dict( + _dict.get('interpretation')) + if 'alternatives' in _dict: + args['alternatives'] = [ + RuntimeEntityAlternative.from_dict(v) + for v in _dict.get('alternatives') + ] + if 'role' in _dict: + args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) + if 'skill' in _dict: + args['skill'] = _dict.get('skill') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'groups') and self.groups is not None: + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list + if hasattr(self, 'interpretation') and self.interpretation is not None: + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list + if hasattr(self, 'role') and self.role is not None: + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntity object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntity') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntity') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityAlternative(): + """ + An alternative value for the recognized entity. + + :attr str value: (optional) The entity value that was recognized in the user + input. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the recognized entity. + """ + + def __init__(self, *, value: str = None, confidence: float = None) -> None: + """ + Initialize a RuntimeEntityAlternative object. + + :param str value: (optional) The entity value that was recognized in the + user input. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized entity. + """ + self.value = value + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + args = {} + if 'value' in _dict: + args['value'] = _dict.get('value') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityAlternative object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityInterpretation(): + """ + RuntimeEntityInterpretation. + + :attr str calendar_type: (optional) The calendar used to represent a recognized + date (for example, `Gregorian`). + :attr str datetime_link: (optional) A unique identifier used to associate a + recognized time and date. If the user input contains a date and time that are + mentioned together (for example, `Today at 5`, the same **datetime_link** value + is returned for both the `@sys-date` and `@sys-time` entities). + :attr str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a `@sys-date` + entity is recognized based on a holiday name in the user input. + :attr str granularity: (optional) The precision or duration of a time range + specified by a recognized `@sys-time` or `@sys-date` entity. + :attr str range_link: (optional) A unique identifier used to associate multiple + recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are + recognized as a range of values in the user's input (for example, `from July 4 + until July 14` or `from 20 to 25`). + :attr str range_modifier: (optional) The word in the user input that indicates + that a `sys-date` or `sys-time` entity is part of an implied range where only + one date or time is specified (for example, `since` or `until`). + :attr float relative_day: (optional) A recognized mention of a relative day, + represented numerically as an offset from the current date (for example, `-1` + for `yesterday` or `10` for `in ten days`). + :attr float relative_month: (optional) A recognized mention of a relative month, + represented numerically as an offset from the current month (for example, `1` + for `next month` or `-3` for `three months ago`). + :attr float relative_week: (optional) A recognized mention of a relative week, + represented numerically as an offset from the current week (for example, `2` for + `in two weeks` or `-1` for `last week). + :attr float relative_weekend: (optional) A recognized mention of a relative date + range for a weekend, represented numerically as an offset from the current + weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). + :attr float relative_year: (optional) A recognized mention of a relative year, + represented numerically as an offset from the current year (for example, `1` for + `next year` or `-5` for `five years ago`). + :attr float specific_day: (optional) A recognized mention of a specific date, + represented numerically as the date within the month (for example, `30` for + `June 30`.). + :attr str specific_day_of_week: (optional) A recognized mention of a specific + day of the week as a lowercase string (for example, `monday`). + :attr float specific_month: (optional) A recognized mention of a specific month, + represented numerically (for example, `7` for `July`). + :attr float specific_quarter: (optional) A recognized mention of a specific + quarter, represented numerically (for example, `3` for `the third quarter`). + :attr float specific_year: (optional) A recognized mention of a specific year + (for example, `2016`). + :attr float numeric_value: (optional) A recognized numeric value, represented as + an integer or double. + :attr str subtype: (optional) The type of numeric value recognized in the user + input (`integer` or `rational`). + :attr str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` or + `afternoon`). + :attr float relative_hour: (optional) A recognized mention of a relative hour, + represented numerically as an offset from the current hour (for example, `3` for + `in three hours` or `-1` for `an hour ago`). + :attr float relative_minute: (optional) A recognized mention of a relative time, + represented numerically as an offset in minutes from the current time (for + example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). + :attr float relative_second: (optional) A recognized mention of a relative time, + represented numerically as an offset in seconds from the current time (for + example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :attr float specific_hour: (optional) A recognized specific hour mentioned as + part of a time value (for example, `10` for `10:15 AM`.). + :attr float specific_minute: (optional) A recognized specific minute mentioned + as part of a time value (for example, `15` for `10:15 AM`.). + :attr float specific_second: (optional) A recognized specific second mentioned + as part of a time value (for example, `30` for `10:15:30 AM`.). + :attr str timezone: (optional) A recognized time zone mentioned as part of a + time value (for example, `EST`). + """ + + def __init__(self, + *, + calendar_type: str = None, + datetime_link: str = None, + festival: str = None, + granularity: str = None, + range_link: str = None, + range_modifier: str = None, + relative_day: float = None, + relative_month: float = None, + relative_week: float = None, + relative_weekend: float = None, + relative_year: float = None, + specific_day: float = None, + specific_day_of_week: str = None, + specific_month: float = None, + specific_quarter: float = None, + specific_year: float = None, + numeric_value: float = None, + subtype: str = None, + part_of_day: str = None, + relative_hour: float = None, + relative_minute: float = None, + relative_second: float = None, + specific_hour: float = None, + specific_minute: float = None, + specific_second: float = None, + timezone: str = None) -> None: + """ + Initialize a RuntimeEntityInterpretation object. + + :param str calendar_type: (optional) The calendar used to represent a + recognized date (for example, `Gregorian`). + :param str datetime_link: (optional) A unique identifier used to associate + a recognized time and date. If the user input contains a date and time that + are mentioned together (for example, `Today at 5`, the same + **datetime_link** value is returned for both the `@sys-date` and + `@sys-time` entities). + :param str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a + `@sys-date` entity is recognized based on a holiday name in the user input. + :param str granularity: (optional) The precision or duration of a time + range specified by a recognized `@sys-time` or `@sys-date` entity. + :param str range_link: (optional) A unique identifier used to associate multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are recognized as a range of values in the user's input (for example, `from July 4 until July 14` or `from 20 to 25`). @@ -4531,158 +7901,2724 @@ def __init__(self, :param str timezone: (optional) A recognized time zone mentioned as part of a time value (for example, `EST`). """ - self.calendar_type = calendar_type - self.datetime_link = datetime_link - self.festival = festival - self.granularity = granularity - self.range_link = range_link - self.range_modifier = range_modifier - self.relative_day = relative_day - self.relative_month = relative_month - self.relative_week = relative_week - self.relative_weekend = relative_weekend - self.relative_year = relative_year - self.specific_day = specific_day - self.specific_day_of_week = specific_day_of_week - self.specific_month = specific_month - self.specific_quarter = specific_quarter - self.specific_year = specific_year - self.numeric_value = numeric_value - self.subtype = subtype - self.part_of_day = part_of_day - self.relative_hour = relative_hour - self.relative_minute = relative_minute - self.relative_second = relative_second - self.specific_hour = specific_hour - self.specific_minute = specific_minute - self.specific_second = specific_second - self.timezone = timezone + self.calendar_type = calendar_type + self.datetime_link = datetime_link + self.festival = festival + self.granularity = granularity + self.range_link = range_link + self.range_modifier = range_modifier + self.relative_day = relative_day + self.relative_month = relative_month + self.relative_week = relative_week + self.relative_weekend = relative_weekend + self.relative_year = relative_year + self.specific_day = specific_day + self.specific_day_of_week = specific_day_of_week + self.specific_month = specific_month + self.specific_quarter = specific_quarter + self.specific_year = specific_year + self.numeric_value = numeric_value + self.subtype = subtype + self.part_of_day = part_of_day + self.relative_hour = relative_hour + self.relative_minute = relative_minute + self.relative_second = relative_second + self.specific_hour = specific_hour + self.specific_minute = specific_minute + self.specific_second = specific_second + self.timezone = timezone + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + args = {} + if 'calendar_type' in _dict: + args['calendar_type'] = _dict.get('calendar_type') + if 'datetime_link' in _dict: + args['datetime_link'] = _dict.get('datetime_link') + if 'festival' in _dict: + args['festival'] = _dict.get('festival') + if 'granularity' in _dict: + args['granularity'] = _dict.get('granularity') + if 'range_link' in _dict: + args['range_link'] = _dict.get('range_link') + if 'range_modifier' in _dict: + args['range_modifier'] = _dict.get('range_modifier') + if 'relative_day' in _dict: + args['relative_day'] = _dict.get('relative_day') + if 'relative_month' in _dict: + args['relative_month'] = _dict.get('relative_month') + if 'relative_week' in _dict: + args['relative_week'] = _dict.get('relative_week') + if 'relative_weekend' in _dict: + args['relative_weekend'] = _dict.get('relative_weekend') + if 'relative_year' in _dict: + args['relative_year'] = _dict.get('relative_year') + if 'specific_day' in _dict: + args['specific_day'] = _dict.get('specific_day') + if 'specific_day_of_week' in _dict: + args['specific_day_of_week'] = _dict.get('specific_day_of_week') + if 'specific_month' in _dict: + args['specific_month'] = _dict.get('specific_month') + if 'specific_quarter' in _dict: + args['specific_quarter'] = _dict.get('specific_quarter') + if 'specific_year' in _dict: + args['specific_year'] = _dict.get('specific_year') + if 'numeric_value' in _dict: + args['numeric_value'] = _dict.get('numeric_value') + if 'subtype' in _dict: + args['subtype'] = _dict.get('subtype') + if 'part_of_day' in _dict: + args['part_of_day'] = _dict.get('part_of_day') + if 'relative_hour' in _dict: + args['relative_hour'] = _dict.get('relative_hour') + if 'relative_minute' in _dict: + args['relative_minute'] = _dict.get('relative_minute') + if 'relative_second' in _dict: + args['relative_second'] = _dict.get('relative_second') + if 'specific_hour' in _dict: + args['specific_hour'] = _dict.get('specific_hour') + if 'specific_minute' in _dict: + args['specific_minute'] = _dict.get('specific_minute') + if 'specific_second' in _dict: + args['specific_second'] = _dict.get('specific_second') + if 'timezone' in _dict: + args['timezone'] = _dict.get('timezone') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'calendar_type') and self.calendar_type is not None: + _dict['calendar_type'] = self.calendar_type + if hasattr(self, 'datetime_link') and self.datetime_link is not None: + _dict['datetime_link'] = self.datetime_link + if hasattr(self, 'festival') and self.festival is not None: + _dict['festival'] = self.festival + if hasattr(self, 'granularity') and self.granularity is not None: + _dict['granularity'] = self.granularity + if hasattr(self, 'range_link') and self.range_link is not None: + _dict['range_link'] = self.range_link + if hasattr(self, 'range_modifier') and self.range_modifier is not None: + _dict['range_modifier'] = self.range_modifier + if hasattr(self, 'relative_day') and self.relative_day is not None: + _dict['relative_day'] = self.relative_day + if hasattr(self, 'relative_month') and self.relative_month is not None: + _dict['relative_month'] = self.relative_month + if hasattr(self, 'relative_week') and self.relative_week is not None: + _dict['relative_week'] = self.relative_week + if hasattr(self, + 'relative_weekend') and self.relative_weekend is not None: + _dict['relative_weekend'] = self.relative_weekend + if hasattr(self, 'relative_year') and self.relative_year is not None: + _dict['relative_year'] = self.relative_year + if hasattr(self, 'specific_day') and self.specific_day is not None: + _dict['specific_day'] = self.specific_day + if hasattr(self, 'specific_day_of_week' + ) and self.specific_day_of_week is not None: + _dict['specific_day_of_week'] = self.specific_day_of_week + if hasattr(self, 'specific_month') and self.specific_month is not None: + _dict['specific_month'] = self.specific_month + if hasattr(self, + 'specific_quarter') and self.specific_quarter is not None: + _dict['specific_quarter'] = self.specific_quarter + if hasattr(self, 'specific_year') and self.specific_year is not None: + _dict['specific_year'] = self.specific_year + if hasattr(self, 'numeric_value') and self.numeric_value is not None: + _dict['numeric_value'] = self.numeric_value + if hasattr(self, 'subtype') and self.subtype is not None: + _dict['subtype'] = self.subtype + if hasattr(self, 'part_of_day') and self.part_of_day is not None: + _dict['part_of_day'] = self.part_of_day + if hasattr(self, 'relative_hour') and self.relative_hour is not None: + _dict['relative_hour'] = self.relative_hour + if hasattr(self, + 'relative_minute') and self.relative_minute is not None: + _dict['relative_minute'] = self.relative_minute + if hasattr(self, + 'relative_second') and self.relative_second is not None: + _dict['relative_second'] = self.relative_second + if hasattr(self, 'specific_hour') and self.specific_hour is not None: + _dict['specific_hour'] = self.specific_hour + if hasattr(self, + 'specific_minute') and self.specific_minute is not None: + _dict['specific_minute'] = self.specific_minute + if hasattr(self, + 'specific_second') and self.specific_second is not None: + _dict['specific_second'] = self.specific_second + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityInterpretation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class GranularityEnum(str, Enum): + """ + The precision or duration of a time range specified by a recognized `@sys-time` or + `@sys-date` entity. + """ + DAY = 'day' + FORTNIGHT = 'fortnight' + HOUR = 'hour' + INSTANT = 'instant' + MINUTE = 'minute' + MONTH = 'month' + QUARTER = 'quarter' + SECOND = 'second' + WEEK = 'week' + WEEKEND = 'weekend' + YEAR = 'year' + + +class RuntimeEntityRole(): + """ + An object describing the role played by a system entity that is specifies the + beginning or end of a range recognized in the user input. This property is included + only if the new system entities are enabled for the skill. + + :attr str type: (optional) The relationship of the entity to the range. + """ + + def __init__(self, *, type: str = None) -> None: + """ + Initialize a RuntimeEntityRole object. + + :param str type: (optional) The relationship of the entity to the range. + """ + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': + """Initialize a RuntimeEntityRole object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityRole object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityRole object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The relationship of the entity to the range. + """ + DATE_FROM = 'date_from' + DATE_TO = 'date_to' + NUMBER_FROM = 'number_from' + NUMBER_TO = 'number_to' + TIME_FROM = 'time_from' + TIME_TO = 'time_to' + + +class RuntimeIntent(): + """ + An intent identified in the user input. + + :attr str intent: The name of the recognized intent. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :attr str skill: (optional) The skill that identified the intent. Currently, the + only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__(self, + intent: str, + *, + confidence: float = None, + skill: str = None) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the intent. If you are specifying an intent as part + of a request, but you do not have a calculated confidence value, specify + `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.intent = intent + self.confidence = confidence + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + if 'intent' in _dict: + args['intent'] = _dict.get('intent') + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'skill' in _dict: + args['skill'] = _dict.get('skill') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeIntent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeIntent') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric(): + """ + RuntimeResponseGeneric. + + """ + + def __init__(self) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class SearchResult(): + """ + SearchResult. + + :attr str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :attr SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :attr str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :attr str title: (optional) The title of the search result. This is taken from a + title or name field in the Discovery service response, as specified in the + search skill configuration. + :attr str url: (optional) The URL of the original data object in its native data + source. + :attr SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :attr List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + + def __init__(self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: str = None, + title: str = None, + url: str = None, + highlight: 'SearchResultHighlight' = None, + answers: List['SearchResultAnswer'] = None) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if 'id' in _dict: + args['id'] = _dict.get('id') + else: + raise ValueError( + 'Required property \'id\' not present in SearchResult JSON') + if 'result_metadata' in _dict: + args['result_metadata'] = SearchResultMetadata.from_dict( + _dict.get('result_metadata')) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if 'body' in _dict: + args['body'] = _dict.get('body') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'url' in _dict: + args['url'] = _dict.get('url') + if 'highlight' in _dict: + args['highlight'] = SearchResultHighlight.from_dict( + _dict.get('highlight')) + if 'answers' in _dict: + args['answers'] = [ + SearchResultAnswer.from_dict(v) for v in _dict.get('answers') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultAnswer(): + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :attr str text: The text of the answer. + :attr float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__(self, text: str, confidence: float) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" + args = {} + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultAnswer object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResultAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultHighlight(): + """ + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. + + :attr List[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :attr List[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :attr List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. + """ + + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + + def __init__(self, + *, + body: List[str] = None, + title: List[str] = None, + url: List[str] = None, + **kwargs) -> None: + """ + Initialize a SearchResultHighlight object. + + :param List[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param **kwargs: (optional) Any additional properties. + """ + self.body = body + self.title = title + self.url = url + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" + args = {} + if 'body' in _dict: + args['body'] = _dict.get('body') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'url' in _dict: + args['url'] = _dict.get('url') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in SearchResultHighlight._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this SearchResultHighlight object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultMetadata(): + """ + An object containing search result metadata from the Discovery service. + + :attr float confidence: (optional) The confidence score for the given result, as + returned by the Discovery service. + :attr float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + """ + + def __init__(self, + *, + confidence: float = None, + score: float = None) -> None: + """ + Initialize a SearchResultMetadata object. + + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. + """ + self.confidence = confidence + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" + args = {} + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'score' in _dict: + args['score'] = _dict.get('score') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettings(): + """ + An object describing the search skill configuration. + + :attr SearchSettingsDiscovery discovery: Configuration settings for the Watson + Discovery service instance used by the search integration. + :attr SearchSettingsMessages messages: The messages included with responses from + the search integration. + :attr SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + the Watson Discovery collection and properties in the search response. + """ + + def __init__(self, discovery: 'SearchSettingsDiscovery', + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping') -> None: + """ + Initialize a SearchSettings object. + + :param SearchSettingsDiscovery discovery: Configuration settings for the + Watson Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with + responses from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between + fields in the Watson Discovery collection and properties in the search + response. + """ + self.discovery = discovery + self.messages = messages + self.schema_mapping = schema_mapping + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettings': + """Initialize a SearchSettings object from a json dictionary.""" + args = {} + if 'discovery' in _dict: + args['discovery'] = SearchSettingsDiscovery.from_dict( + _dict.get('discovery')) + else: + raise ValueError( + 'Required property \'discovery\' not present in SearchSettings JSON' + ) + if 'messages' in _dict: + args['messages'] = SearchSettingsMessages.from_dict( + _dict.get('messages')) + else: + raise ValueError( + 'Required property \'messages\' not present in SearchSettings JSON' + ) + if 'schema_mapping' in _dict: + args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( + _dict.get('schema_mapping')) + else: + raise ValueError( + 'Required property \'schema_mapping\' not present in SearchSettings JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettings object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'discovery') and self.discovery is not None: + if isinstance(self.discovery, dict): + _dict['discovery'] = self.discovery + else: + _dict['discovery'] = self.discovery.to_dict() + if hasattr(self, 'messages') and self.messages is not None: + if isinstance(self.messages, dict): + _dict['messages'] = self.messages + else: + _dict['messages'] = self.messages.to_dict() + if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: + if isinstance(self.schema_mapping, dict): + _dict['schema_mapping'] = self.schema_mapping + else: + _dict['schema_mapping'] = self.schema_mapping.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettings object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettings') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettings') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscovery(): + """ + Configuration settings for the Watson Discovery service instance used by the search + integration. + + :attr str instance_id: The ID for the Watson Discovery service instance. + :attr str project_id: The ID for the Watson Discovery project. + :attr str url: The URL for the Watson Discovery service instance. + :attr int max_primary_results: (optional) The maximum number of primary results + to include in the response. + :attr int max_total_results: (optional) The maximum total number of primary and + additional results to include in the response. + :attr float confidence_threshold: (optional) The minimum confidence threshold + for included results. Any results with a confidence below this threshold will be + discarded. + :attr bool highlight: (optional) Whether to include the most relevant passages + of text in the **highlight** property of each result. + :attr bool find_answers: (optional) Whether to use the answer finding feature to + emphasize answers within highlighted passages. This property is ignored if + **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + :attr SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + """ + + def __init__(self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: int = None, + max_total_results: int = None, + confidence_threshold: float = None, + highlight: bool = None, + find_answers: bool = None) -> None: + """ + Initialize a SearchSettingsDiscovery object. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + :param int max_primary_results: (optional) The maximum number of primary + results to include in the response. + :param int max_total_results: (optional) The maximum total number of + primary and additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence + threshold for included results. Any results with a confidence below this + threshold will be discarded. + :param bool highlight: (optional) Whether to include the most relevant + passages of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding + feature to emphasize answers within highlighted passages. This property is + ignored if **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.instance_id = instance_id + self.project_id = project_id + self.url = url + self.max_primary_results = max_primary_results + self.max_total_results = max_total_results + self.confidence_threshold = confidence_threshold + self.highlight = highlight + self.find_answers = find_answers + self.authentication = authentication + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + args = {} + if 'instance_id' in _dict: + args['instance_id'] = _dict.get('instance_id') + else: + raise ValueError( + 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' + ) + if 'project_id' in _dict: + args['project_id'] = _dict.get('project_id') + else: + raise ValueError( + 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' + ) + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + ) + if 'max_primary_results' in _dict: + args['max_primary_results'] = _dict.get('max_primary_results') + if 'max_total_results' in _dict: + args['max_total_results'] = _dict.get('max_total_results') + if 'confidence_threshold' in _dict: + args['confidence_threshold'] = _dict.get('confidence_threshold') + if 'highlight' in _dict: + args['highlight'] = _dict.get('highlight') + if 'find_answers' in _dict: + args['find_answers'] = _dict.get('find_answers') + if 'authentication' in _dict: + args[ + 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( + _dict.get('authentication')) + else: + raise ValueError( + 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'instance_id') and self.instance_id is not None: + _dict['instance_id'] = self.instance_id + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr( + self, + 'max_primary_results') and self.max_primary_results is not None: + _dict['max_primary_results'] = self.max_primary_results + if hasattr(self, + 'max_total_results') and self.max_total_results is not None: + _dict['max_total_results'] = self.max_total_results + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsDiscovery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscoveryAuthentication(): + """ + Authentication information for the Watson Discovery service. For more information, see + the [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + + :attr str basic: (optional) The HTTP basic authentication credentials for Watson + Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :attr str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + + def __init__(self, *, basic: str = None, bearer: str = None) -> None: + """ + Initialize a SearchSettingsDiscoveryAuthentication object. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + self.basic = basic + self.bearer = bearer + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + args = {} + if 'basic' in _dict: + args['basic'] = _dict.get('basic') + if 'bearer' in _dict: + args['bearer'] = _dict.get('bearer') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'basic') and self.basic is not None: + _dict['basic'] = self.basic + if hasattr(self, 'bearer') and self.bearer is not None: + _dict['bearer'] = self.bearer + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsDiscoveryAuthentication object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsMessages(): + """ + The messages included with responses from the search integration. + + :attr str success: The message to include in the response to a successful query. + :attr str error: The message to include in the response when the query + encounters an error. + :attr str no_result: The message to include in the response when there is no + result from the query. + """ + + def __init__(self, success: str, error: str, no_result: str) -> None: + """ + Initialize a SearchSettingsMessages object. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is + no result from the query. + """ + self.success = success + self.error = error + self.no_result = no_result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': + """Initialize a SearchSettingsMessages object from a json dictionary.""" + args = {} + if 'success' in _dict: + args['success'] = _dict.get('success') + else: + raise ValueError( + 'Required property \'success\' not present in SearchSettingsMessages JSON' + ) + if 'error' in _dict: + args['error'] = _dict.get('error') + else: + raise ValueError( + 'Required property \'error\' not present in SearchSettingsMessages JSON' + ) + if 'no_result' in _dict: + args['no_result'] = _dict.get('no_result') + else: + raise ValueError( + 'Required property \'no_result\' not present in SearchSettingsMessages JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsMessages object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'no_result') and self.no_result is not None: + _dict['no_result'] = self.no_result + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsMessages object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsSchemaMapping(): + """ + The mapping between fields in the Watson Discovery collection and properties in the + search response. + + :attr str url: The field in the collection to map to the **url** property of the + response. + :attr str body: The field in the collection to map to the **body** property in + the response. + :attr str title: The field in the collection to map to the **title** property + for the schema. + """ + + def __init__(self, url: str, body: str, title: str) -> None: + """ + Initialize a SearchSettingsSchemaMapping object. + + :param str url: The field in the collection to map to the **url** property + of the response. + :param str body: The field in the collection to map to the **body** + property in the response. + :param str title: The field in the collection to map to the **title** + property for the schema. + """ + self.url = url + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + args = {} + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' + ) + if 'body' in _dict: + args['body'] = _dict.get('body') + else: + raise ValueError( + 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + else: + raise ValueError( + 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSettingsSchemaMapping object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSkillWarning(): + """ + A warning describing an error in the search skill configuration. + + :attr str code: (optional) The error code. + :attr str path: (optional) The location of the error in the search skill + configuration object. + :attr str message: (optional) The error message. + """ + + def __init__(self, + *, + code: str = None, + path: str = None, + message: str = None) -> None: + """ + Initialize a SearchSkillWarning object. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + self.code = code + self.path = path + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': + """Initialize a SearchSkillWarning object from a json dictionary.""" + args = {} + if 'code' in _dict: + args['code'] = _dict.get('code') + if 'path' in _dict: + args['path'] = _dict.get('path') + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSkillWarning object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchSkillWarning object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SessionResponse(): + """ + SessionResponse. + + :attr str session_id: The session ID. + """ + + def __init__(self, session_id: str) -> None: + """ + Initialize a SessionResponse object. + + :param str session_id: The session ID. + """ + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" + args = {} + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') + else: + raise ValueError( + 'Required property \'session_id\' not present in SessionResponse JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SessionResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SessionResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SessionResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SessionResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Skill(): + """ + Skill. + + :attr str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :attr str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :attr dict workspace: (optional) An object containing the conversational content + of an action or dialog skill. + :attr str skill_id: (optional) The skill ID of the skill. + :attr str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :attr str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :attr dict dialog_settings: (optional) For internal use only. + :attr str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :attr str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :attr str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :attr bool valid: (optional) Whether the skill is structurally valid. + :attr str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :attr SearchSettings search_settings: (optional) An object describing the search + skill configuration. + :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :attr str language: The language of the skill. + :attr str type: The type of skill. + """ + + def __init__(self, + language: str, + type: str, + *, + name: str = None, + description: str = None, + workspace: dict = None, + skill_id: str = None, + status: str = None, + status_errors: List['StatusError'] = None, + status_description: str = None, + dialog_settings: dict = None, + assistant_id: str = None, + workspace_id: str = None, + environment_id: str = None, + valid: bool = None, + next_snapshot_version: str = None, + search_settings: 'SearchSettings' = None, + warnings: List['SearchSkillWarning'] = None) -> None: + """ + Initialize a Skill object. + + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Skill': + """Initialize a Skill object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'workspace' in _dict: + args['workspace'] = _dict.get('workspace') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(v) for v in _dict.get('status_errors') + ] + if 'status_description' in _dict: + args['status_description'] = _dict.get('status_description') + if 'dialog_settings' in _dict: + args['dialog_settings'] = _dict.get('dialog_settings') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'valid' in _dict: + args['valid'] = _dict.get('valid') + if 'next_snapshot_version' in _dict: + args['next_snapshot_version'] = _dict.get('next_snapshot_version') + if 'search_settings' in _dict: + args['search_settings'] = SearchSettings.from_dict( + _dict.get('search_settings')) + if 'warnings' in _dict: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + ] + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in Skill JSON') + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in Skill JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Skill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Skill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Skill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Skill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' + + +class SkillImport(): + """ + SkillImport. + + :attr str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :attr str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :attr dict workspace: (optional) An object containing the conversational content + of an action or dialog skill. + :attr str skill_id: (optional) The skill ID of the skill. + :attr str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :attr str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :attr dict dialog_settings: (optional) For internal use only. + :attr str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :attr str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :attr str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :attr bool valid: (optional) Whether the skill is structurally valid. + :attr str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :attr SearchSettings search_settings: (optional) An object describing the search + skill configuration. + :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :attr str language: The language of the skill. + :attr str type: The type of skill. + """ + + def __init__(self, + language: str, + type: str, + *, + name: str = None, + description: str = None, + workspace: dict = None, + skill_id: str = None, + status: str = None, + status_errors: List['StatusError'] = None, + status_description: str = None, + dialog_settings: dict = None, + assistant_id: str = None, + workspace_id: str = None, + environment_id: str = None, + valid: bool = None, + next_snapshot_version: str = None, + search_settings: 'SearchSettings' = None, + warnings: List['SearchSkillWarning'] = None) -> None: + """ + Initialize a SkillImport object. + + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillImport': + """Initialize a SkillImport object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'workspace' in _dict: + args['workspace'] = _dict.get('workspace') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(v) for v in _dict.get('status_errors') + ] + if 'status_description' in _dict: + args['status_description'] = _dict.get('status_description') + if 'dialog_settings' in _dict: + args['dialog_settings'] = _dict.get('dialog_settings') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'valid' in _dict: + args['valid'] = _dict.get('valid') + if 'next_snapshot_version' in _dict: + args['next_snapshot_version'] = _dict.get('next_snapshot_version') + if 'search_settings' in _dict: + args['search_settings'] = SearchSettings.from_dict( + _dict.get('search_settings')) + if 'warnings' in _dict: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + ] + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in SkillImport JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in SkillImport JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillImport object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillImport object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillImport') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillImport') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' + + +class SkillsAsyncRequestStatus(): + """ + SkillsAsyncRequestStatus. + + :attr str assistant_id: (optional) The assistant ID of the assistant. + :attr str status: (optional) The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + :attr str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + """ + + def __init__(self, + *, + assistant_id: str = None, + status: str = None, + status_description: str = None, + status_errors: List['StatusError'] = None) -> None: + """ + Initialize a SkillsAsyncRequestStatus object. + + """ + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + args = {} + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'status_description' in _dict: + args['status_description'] = _dict.get('status_description') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(v) for v in _dict.get('status_errors') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillsAsyncRequestStatus object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + """ + AVAILABLE = 'Available' + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class SkillsExport(): + """ + SkillsExport. + + :attr List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :attr AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. + """ + + def __init__(self, assistant_skills: List['Skill'], + assistant_state: 'AssistantState') -> None: + """ + Initialize a SkillsExport object. + + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + """ + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" + args = {} + if 'assistant_skills' in _dict: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in _dict.get('assistant_skills') + ] + else: + raise ValueError( + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if 'assistant_state' in _dict: + args['assistant_state'] = AssistantState.from_dict( + _dict.get('assistant_state')) + else: + raise ValueError( + 'Required property \'assistant_state\' not present in SkillsExport JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillsExport object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SkillsExport object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillsExport') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SkillsExport') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatusError(): + """ + An object describing an error that occurred during processing of an asynchronous + operation. + + :attr str message: (optional) The text of the error message. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a StatusError object. + + :param str message: (optional) The text of the error message. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatusError object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StatusError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatusError') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StatusError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TurnEventActionSource(): + """ + TurnEventActionSource. + + :attr str type: (optional) The type of turn event. + :attr str action: (optional) An action that was visited during processing of the + message. + :attr str action_title: (optional) The title of the action. + :attr str condition: (optional) The condition that triggered the dialog node. + """ + + def __init__(self, + *, + type: str = None, + action: str = None, + action_title: str = None, + condition: str = None) -> None: + """ + Initialize a TurnEventActionSource object. + + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog + node. + """ + self.type = type + self.action = action + self.action_title = action_title + self.condition = condition + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': + """Initialize a TurnEventActionSource object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'action' in _dict: + args['action'] = _dict.get('action') + if 'action_title' in _dict: + args['action_title'] = _dict.get('action_title') + if 'condition' in _dict: + args['condition'] = _dict.get('condition') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventActionSource object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TurnEventActionSource object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventActionSource') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TurnEventActionSource') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + ACTION = 'action' + + +class TurnEventCalloutCallout(): + """ + TurnEventCalloutCallout. + + :attr str type: (optional) The type of callout. Currently, the only supported + value is `integration_interaction` (for calls to extensions). + :attr dict internal: (optional) For internal use only. + :attr str result_variable: (optional) The name of the variable where the callout + result is stored. + """ + + def __init__(self, + *, + type: str = None, + internal: dict = None, + result_variable: str = None) -> None: + """ + Initialize a TurnEventCalloutCallout object. + + :param str type: (optional) The type of callout. Currently, the only + supported value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + """ + self.type = type + self.internal = internal + self.result_variable = result_variable + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'internal' in _dict: + args['internal'] = _dict.get('internal') + if 'result_variable' in _dict: + args['result_variable'] = _dict.get('result_variable') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'internal') and self.internal is not None: + _dict['internal'] = self.internal + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TurnEventCalloutCallout object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventCalloutCallout') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TurnEventCalloutCallout') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of callout. Currently, the only supported value is + `integration_interaction` (for calls to extensions). + """ + INTEGRATION_INTERACTION = 'integration_interaction' + + +class TurnEventCalloutError(): + """ + TurnEventCalloutError. + + :attr str message: (optional) Any error message returned by a failed call to an + external service. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a TurnEventCalloutError object. + + :param str message: (optional) Any error message returned by a failed call + to an external service. + """ + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': + """Initialize a TurnEventCalloutError object from a json dictionary.""" args = {} - if 'calendar_type' in _dict: - args['calendar_type'] = _dict.get('calendar_type') - if 'datetime_link' in _dict: - args['datetime_link'] = _dict.get('datetime_link') - if 'festival' in _dict: - args['festival'] = _dict.get('festival') - if 'granularity' in _dict: - args['granularity'] = _dict.get('granularity') - if 'range_link' in _dict: - args['range_link'] = _dict.get('range_link') - if 'range_modifier' in _dict: - args['range_modifier'] = _dict.get('range_modifier') - if 'relative_day' in _dict: - args['relative_day'] = _dict.get('relative_day') - if 'relative_month' in _dict: - args['relative_month'] = _dict.get('relative_month') - if 'relative_week' in _dict: - args['relative_week'] = _dict.get('relative_week') - if 'relative_weekend' in _dict: - args['relative_weekend'] = _dict.get('relative_weekend') - if 'relative_year' in _dict: - args['relative_year'] = _dict.get('relative_year') - if 'specific_day' in _dict: - args['specific_day'] = _dict.get('specific_day') - if 'specific_day_of_week' in _dict: - args['specific_day_of_week'] = _dict.get('specific_day_of_week') - if 'specific_month' in _dict: - args['specific_month'] = _dict.get('specific_month') - if 'specific_quarter' in _dict: - args['specific_quarter'] = _dict.get('specific_quarter') - if 'specific_year' in _dict: - args['specific_year'] = _dict.get('specific_year') - if 'numeric_value' in _dict: - args['numeric_value'] = _dict.get('numeric_value') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') - if 'part_of_day' in _dict: - args['part_of_day'] = _dict.get('part_of_day') - if 'relative_hour' in _dict: - args['relative_hour'] = _dict.get('relative_hour') - if 'relative_minute' in _dict: - args['relative_minute'] = _dict.get('relative_minute') - if 'relative_second' in _dict: - args['relative_second'] = _dict.get('relative_second') - if 'specific_hour' in _dict: - args['specific_hour'] = _dict.get('specific_hour') - if 'specific_minute' in _dict: - args['specific_minute'] = _dict.get('specific_minute') - if 'specific_second' in _dict: - args['specific_second'] = _dict.get('specific_second') - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventCalloutError object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TurnEventCalloutError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventCalloutError') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TurnEventCalloutError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TurnEventNodeSource(): + """ + TurnEventNodeSource. + + :attr str type: (optional) The type of turn event. + :attr str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :attr str title: (optional) The title of the dialog node. + :attr str condition: (optional) The condition that triggered the dialog node. + """ + + def __init__(self, + *, + type: str = None, + dialog_node: str = None, + title: str = None, + condition: str = None) -> None: + """ + Initialize a TurnEventNodeSource object. + + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog + node. + """ + self.type = type + self.dialog_node = dialog_node + self.title = title + self.condition = condition + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': + """Initialize a TurnEventNodeSource object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'condition' in _dict: + args['condition'] = _dict.get('condition') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventNodeSource object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TurnEventNodeSource object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventNodeSource') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TurnEventNodeSource') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + DIALOG_NODE = 'dialog_node' + + +class TurnEventSearchError(): + """ + TurnEventSearchError. + + :attr str message: (optional) Any error message returned by a failed call to a + search skill. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a TurnEventSearchError object. + + :param str message: (optional) Any error message returned by a failed call + to a search skill. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': + """Initialize a TurnEventSearchError object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventSearchError object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TurnEventSearchError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventSearchError') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TurnEventSearchError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceAction(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + """ + + def __init__(self, type: str, action: str) -> None: + """ + Initialize a LogMessageSourceAction object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + """ + # pylint: disable=super-init-not-called + self.type = type + self.action = action + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': + """Initialize a LogMessageSourceAction object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceAction JSON' + ) + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceAction JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a LogMessageSourceAction object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'calendar_type') and self.calendar_type is not None: - _dict['calendar_type'] = self.calendar_type - if hasattr(self, 'datetime_link') and self.datetime_link is not None: - _dict['datetime_link'] = self.datetime_link - if hasattr(self, 'festival') and self.festival is not None: - _dict['festival'] = self.festival - if hasattr(self, 'granularity') and self.granularity is not None: - _dict['granularity'] = self.granularity - if hasattr(self, 'range_link') and self.range_link is not None: - _dict['range_link'] = self.range_link - if hasattr(self, 'range_modifier') and self.range_modifier is not None: - _dict['range_modifier'] = self.range_modifier - if hasattr(self, 'relative_day') and self.relative_day is not None: - _dict['relative_day'] = self.relative_day - if hasattr(self, 'relative_month') and self.relative_month is not None: - _dict['relative_month'] = self.relative_month - if hasattr(self, 'relative_week') and self.relative_week is not None: - _dict['relative_week'] = self.relative_week - if hasattr(self, - 'relative_weekend') and self.relative_weekend is not None: - _dict['relative_weekend'] = self.relative_weekend - if hasattr(self, 'relative_year') and self.relative_year is not None: - _dict['relative_year'] = self.relative_year - if hasattr(self, 'specific_day') and self.specific_day is not None: - _dict['specific_day'] = self.specific_day - if hasattr(self, 'specific_day_of_week' - ) and self.specific_day_of_week is not None: - _dict['specific_day_of_week'] = self.specific_day_of_week - if hasattr(self, 'specific_month') and self.specific_month is not None: - _dict['specific_month'] = self.specific_month - if hasattr(self, - 'specific_quarter') and self.specific_quarter is not None: - _dict['specific_quarter'] = self.specific_quarter - if hasattr(self, 'specific_year') and self.specific_year is not None: - _dict['specific_year'] = self.specific_year - if hasattr(self, 'numeric_value') and self.numeric_value is not None: - _dict['numeric_value'] = self.numeric_value - if hasattr(self, 'subtype') and self.subtype is not None: - _dict['subtype'] = self.subtype - if hasattr(self, 'part_of_day') and self.part_of_day is not None: - _dict['part_of_day'] = self.part_of_day - if hasattr(self, 'relative_hour') and self.relative_hour is not None: - _dict['relative_hour'] = self.relative_hour - if hasattr(self, - 'relative_minute') and self.relative_minute is not None: - _dict['relative_minute'] = self.relative_minute - if hasattr(self, - 'relative_second') and self.relative_second is not None: - _dict['relative_second'] = self.relative_second - if hasattr(self, 'specific_hour') and self.specific_hour is not None: - _dict['specific_hour'] = self.specific_hour - if hasattr(self, - 'specific_minute') and self.specific_minute is not None: - _dict['specific_minute'] = self.specific_minute - if hasattr(self, - 'specific_second') and self.specific_second is not None: - _dict['specific_second'] = self.specific_second - if hasattr(self, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action return _dict def _to_dict(self): @@ -4690,65 +10626,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this LogMessageSourceAction object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__(self, other: 'LogMessageSourceAction') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __ne__(self, other: 'LogMessageSourceAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, Enum): - """ - The precision or duration of a time range specified by a recognized `@sys-time` or - `@sys-date` entity. - """ - DAY = 'day' - FORTNIGHT = 'fortnight' - HOUR = 'hour' - INSTANT = 'instant' - MINUTE = 'minute' - MONTH = 'month' - QUARTER = 'quarter' - SECOND = 'second' - WEEK = 'week' - WEEKEND = 'weekend' - YEAR = 'year' - -class RuntimeEntityRole(): +class LogMessageSourceDialogNode(LogMessageSource): """ - An object describing the role played by a system entity that is specifies the - beginning or end of a range recognized in the user input. This property is included - only if the new system entities are enabled for the skill. + An object that identifies the dialog element that generated the error message. - :attr str type: (optional) The relationship of the entity to the range. + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str dialog_node: The unique identifier of the dialog node that generated + the error message. """ - def __init__(self, *, type: str = None) -> None: + def __init__(self, type: str, dialog_node: str) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a LogMessageSourceDialogNode object. - :param str type: (optional) The relationship of the entity to the range. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that + generated the error message. """ + # pylint: disable=super-init-not-called self.type = type + self.dialog_node = dialog_node @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' + ) + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + else: + raise ValueError( + 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -4756,6 +10691,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node return _dict def _to_dict(self): @@ -4763,81 +10700,100 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this LogMessageSourceDialogNode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityRole') -> bool: + def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The relationship of the entity to the range. - """ - DATE_FROM = 'date_from' - DATE_TO = 'date_to' - NUMBER_FROM = 'number_from' - NUMBER_TO = 'number_to' - TIME_FROM = 'time_from' - TIME_TO = 'time_to' - -class RuntimeIntent(): +class LogMessageSourceHandler(LogMessageSource): """ - An intent identified in the user input. + An object that identifies the dialog element that generated the error message. - :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + :attr str step: (optional) The unique identifier of the step that generated the + error message. + :attr str handler: The unique identifier of the handler that generated the error + message. """ - def __init__(self, intent: str, confidence: float) -> None: + def __init__(self, + type: str, + action: str, + handler: str, + *, + step: str = None) -> None: """ - Initialize a RuntimeIntent object. + Initialize a LogMessageSourceHandler object. - :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's - confidence in the intent. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. + :param str step: (optional) The unique identifier of the step that + generated the error message. """ - self.intent = intent - self.confidence = confidence + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + self.handler = handler @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': + """Initialize a LogMessageSourceHandler object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if 'type' in _dict: + args['type'] = _dict.get('type') else: raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' + 'Required property \'type\' not present in LogMessageSourceHandler JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceHandler JSON' + ) + if 'step' in _dict: + args['step'] = _dict.get('step') + if 'handler' in _dict: + args['handler'] = _dict.get('handler') else: raise ValueError( - 'Required property \'confidence\' not present in RuntimeIntent JSON' + 'Required property \'handler\' not present in LogMessageSourceHandler JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a LogMessageSourceHandler object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'handler') and self.handler is not None: + _dict['handler'] = self.handler return _dict def _to_dict(self): @@ -4845,240 +10801,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this LogMessageSourceHandler object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGeneric(): +class LogMessageSourceStep(LogMessageSource): """ - RuntimeResponseGeneric. + An object that identifies the dialog element that generated the error message. + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + :attr str step: The unique identifier of the step that generated the error + message. """ - def __init__(self) -> None: + def __init__(self, type: str, action: str, step: str) -> None: """ - Initialize a RuntimeResponseGeneric object. + Initialize a LogMessageSourceStep object. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str step: The unique identifier of the step that generated the error + message. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - return cls.from_dict(_dict) + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': + """Initialize a LogMessageSourceStep object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + else: raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + 'Required property \'type\' not present in LogMessageSourceStep JSON' ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class SearchResult(): - """ - SearchResult. - - :attr str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :attr SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :attr str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :attr str title: (optional) The title of the search result. This is taken from a - title or name field in the Discovery service response, as specified in the - search skill configuration. - :attr str url: (optional) The URL of the original data object in its native data - source. - :attr SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :attr List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Note:** This property uses the answer finding beta feature, and is available - only if the search skill is connected to a Discovery v2 service instance. - """ - - def __init__(self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: str = None, - title: str = None, - url: str = None, - highlight: 'SearchResultHighlight' = None, - answers: List['SearchResultAnswer'] = None) -> None: - """ - Initialize a SearchResult object. - - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Note:** This property uses the answer finding beta feature, and is - available only if the search skill is connected to a Discovery v2 service - instance. - """ - self.id = id - self.result_metadata = result_metadata - self.body = body - self.title = title - self.url = url - self.highlight = highlight - self.answers = answers - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" - args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if 'action' in _dict: + args['action'] = _dict.get('action') else: raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if 'result_metadata' in _dict: - args['result_metadata'] = SearchResultMetadata.from_dict( - _dict.get('result_metadata')) + 'Required property \'action\' not present in LogMessageSourceStep JSON' + ) + if 'step' in _dict: + args['step'] = _dict.get('step') else: raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' + 'Required property \'step\' not present in LogMessageSourceStep JSON' ) - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'highlight' in _dict: - args['highlight'] = SearchResultHighlight.from_dict( - _dict.get('highlight')) - if 'answers' in _dict: - args['answers'] = [ - SearchResultAnswer.from_dict(x) for x in _dict.get('answers') - ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a LogMessageSourceStep object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step return _dict def _to_dict(self): @@ -5086,71 +10888,111 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this LogMessageSourceStep object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResult') -> bool: + def __ne__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer(): +class MessageOutputDebugTurnEventTurnEventActionFinished( + MessageOutputDebugTurnEvent): """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + MessageOutputDebugTurnEventTurnEventActionFinished. - :attr str text: The text of the answer. - :attr float confidence: The confidence score for the answer, as returned by the - Discovery service. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str reason: (optional) The reason the action finished processing. + :attr dict action_variables: (optional) The state of all action variables at the + time the action finished. """ - def __init__(self, text: str, confidence: float) -> None: - """ - Initialize a SearchResultAnswer object. - - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + action_start_time: str = None, + condition_type: str = None, + reason: str = None, + action_variables: dict = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables + at the time the action finished. """ - self.text = text - self.confidence = confidence + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.action_variables = action_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'reason' in _dict: + args['reason'] = _dict.get('reason') + if 'action_variables' in _dict: + args['action_variables'] = _dict.get('action_variables') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables return _dict def _to_dict(self): @@ -5158,191 +11000,254 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultAnswer') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' -class SearchResultHighlight(): - """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. + class ReasonEnum(str, Enum): + """ + The reason the action finished processing. + """ + ALL_STEPS_DONE = 'all_steps_done' + NO_STEPS_VISITED = 'no_steps_visited' + ENDED_BY_STEP = 'ended_by_step' + CONNECT_TO_AGENT = 'connect_to_agent' + MAX_RETRIES_REACHED = 'max_retries_reached' + FALLBACK = 'fallback' - :attr List[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings - highlighted. - :attr List[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings - highlighted. - :attr List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + +class MessageOutputDebugTurnEventTurnEventActionVisited( + MessageOutputDebugTurnEvent): """ + MessageOutputDebugTurnEventTurnEventActionVisited. - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str reason: (optional) The reason the action was visited. + :attr str result_variable: (optional) The variable where the result of the call + to the action is stored. Included only if **reason**=`subaction_return`. + """ def __init__(self, *, - body: List[str] = None, - title: List[str] = None, - url: List[str] = None, - **kwargs) -> None: - """ - Initialize a SearchResultHighlight object. - - :param List[str] body: (optional) An array of strings containing segments - taken from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments - taken from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments - taken from URLs in the search results, with query-matching substrings - highlighted. - :param **kwargs: (optional) Any additional properties. + event: str = None, + source: 'TurnEventActionSource' = None, + action_start_time: str = None, + condition_type: str = None, + reason: str = None, + result_variable: str = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the + call to the action is stored. Included only if + **reason**=`subaction_return`. """ - self.body = body - self.title = title - self.url = url - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.result_variable = result_variable @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'reason' in _dict: + args['reason'] = _dict.get('reason') + if 'result_variable' in _dict: + args['result_variable'] = _dict.get('result_variable') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in SearchResultHighlight._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultHighlight') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' -class SearchResultMetadata(): + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ + INTENT = 'intent' + INVOKE_SUBACTION = 'invoke_subaction' + SUBACTION_RETURN = 'subaction_return' + INVOKE_EXTERNAL = 'invoke_external' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + AGENT_REQUESTED = 'agent_requested' + STEP_VALIDATION_FAILED = 'step_validation_failed' + NO_ACTION_MATCHES = 'no_action_matches' + + +class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ - An object containing search result metadata from the Discovery service. + MessageOutputDebugTurnEventTurnEventCallout. - :attr float confidence: (optional) The confidence score for the given result, as - returned by the Discovery service. - :attr float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr TurnEventCalloutCallout callout: (optional) + :attr TurnEventCalloutError error: (optional) """ def __init__(self, *, - confidence: float = None, - score: float = None) -> None: + event: str = None, + source: 'TurnEventActionSource' = None, + callout: 'TurnEventCalloutCallout' = None, + error: 'TurnEventCalloutError' = None) -> None: """ - Initialize a SearchResultMetadata object. + Initialize a MessageOutputDebugTurnEventTurnEventCallout object. - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - self.confidence = confidence - self.score = score + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.callout = callout + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'score' in _dict: - args['score'] = _dict.get('score') + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'callout' in _dict: + args['callout'] = TurnEventCalloutCallout.from_dict( + _dict.get('callout')) + if 'error' in _dict: + args['error'] = TurnEventCalloutError.from_dict(_dict.get('error')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -5350,57 +11255,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultMetadata') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SessionResponse(): +class MessageOutputDebugTurnEventTurnEventHandlerVisited( + MessageOutputDebugTurnEvent): """ - SessionResponse. + MessageOutputDebugTurnEventTurnEventHandlerVisited. - :attr str session_id: The session ID. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str action_start_time: (optional) The time when the action started + processing the message. """ - def __init__(self, session_id: str) -> None: + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + action_start_time: str = None) -> None: """ - Initialize a SessionResponse object. + Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. - :param str session_id: The session ID. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ - self.session_id = session_id + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') - else: - raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SessionResponse object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time return _dict def _to_dict(self): @@ -5408,73 +11340,82 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SessionResponse object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SessionResponse') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceAction(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventNodeVisited( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventNodeVisited. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. + :attr str event: (optional) The type of turn event. + :attr TurnEventNodeSource source: (optional) + :attr str reason: (optional) The reason the dialog node was visited. """ - def __init__(self, type: str, action: str) -> None: + def __init__(self, + *, + event: str = None, + source: 'TurnEventNodeSource' = None, + reason: str = None) -> None: """ - Initialize a LogMessageSourceAction object. + Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action + self.event = event + self.source = source + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': - """Initialize a LogMessageSourceAction object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceAction JSON' - ) - if 'action' in _dict: - args['action'] = _dict.get('action') - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceAction JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventNodeSource.from_dict(_dict.get('source')) + if 'reason' in _dict: + args['reason'] = _dict.get('reason') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceAction object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -5482,73 +11423,95 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceAction object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceAction') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceAction') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ReasonEnum(str, Enum): + """ + The reason the dialog node was visited. + """ + WELCOME = 'welcome' + BRANCH_START = 'branch_start' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' + JUMP = 'jump' -class LogMessageSourceDialogNode(LogMessageSource): + +class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventSearch. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str dialog_node: The unique identifier of the dialog node that generated - the error message. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr TurnEventSearchError error: (optional) """ - def __init__(self, type: str, dialog_node: str) -> None: + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + error: 'TurnEventSearchError' = None) -> None: """ - Initialize a LogMessageSourceDialogNode object. + Initialize a MessageOutputDebugTurnEventTurnEventSearch object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ # pylint: disable=super-init-not-called - self.type = type - self.dialog_node = dialog_node + self.event = event + self.source = source + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' - ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - else: - raise ValueError( - 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'error' in _dict: + args['error'] = TurnEventSearchError.from_dict(_dict.get('error')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -5556,100 +11519,106 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceDialogNode object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceHandler(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventStepAnswered( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventStepAnswered. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. - :attr str step: (optional) The unique identifier of the step that generated the - error message. - :attr str handler: The unique identifier of the handler that generated the error - message. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr bool prompted: (optional) Whether the step was answered in response to a + prompt from the assistant. If this property is `false`, the user provided the + answer without visiting the step. """ def __init__(self, - type: str, - action: str, - handler: str, *, - step: str = None) -> None: - """ - Initialize a LogMessageSourceHandler object. - - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. - :param str step: (optional) The unique identifier of the step that - generated the error message. + event: str = None, + source: 'TurnEventActionSource' = None, + condition_type: str = None, + action_start_time: str = None, + prompted: bool = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response + to a prompt from the assistant. If this property is `false`, the user + provided the answer without visiting the step. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step - self.handler = handler + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.prompted = prompted @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceHandler JSON' - ) - if 'action' in _dict: - args['action'] = _dict.get('action') - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceHandler JSON' - ) - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'handler' in _dict: - args['handler'] = _dict.get('handler') - else: - raise ValueError( - 'Required property \'handler\' not present in LogMessageSourceHandler JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'prompted' in _dict: + args['prompted'] = _dict.get('prompted') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'handler') and self.handler is not None: - _dict['handler'] = self.handler + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'prompted') and self.prompted is not None: + _dict['prompted'] = self.prompted return _dict def _to_dict(self): @@ -5657,86 +11626,114 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceHandler object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceHandler') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceHandler') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' -class LogMessageSourceStep(LogMessageSource): - """ - An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. - :attr str step: The unique identifier of the step that generated the error - message. +class MessageOutputDebugTurnEventTurnEventStepVisited( + MessageOutputDebugTurnEvent): """ + MessageOutputDebugTurnEventTurnEventStepVisited. - def __init__(self, type: str, action: str, step: str) -> None: - """ - Initialize a LogMessageSourceStep object. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr bool has_question: (optional) Whether the step collects a customer + response. + """ - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str step: The unique identifier of the step that generated the error - message. + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + condition_type: str = None, + action_start_time: str = None, + has_question: bool = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.has_question = has_question @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': - """Initialize a LogMessageSourceStep object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceStep JSON' - ) - if 'action' in _dict: - args['action'] = _dict.get('action') - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceStep JSON' - ) - if 'step' in _dict: - args['step'] = _dict.get('step') - else: - raise ValueError( - 'Required property \'step\' not present in LogMessageSourceStep JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'has_question' in _dict: + args['has_question'] = _dict.get('has_question') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceStep object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'has_question') and self.has_question is not None: + _dict['has_question'] = self.has_question return _dict def _to_dict(self): @@ -5744,19 +11741,31 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceStep object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceStep') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceStep') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ @@ -5772,7 +11781,7 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -5784,7 +11793,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -5801,7 +11810,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -5838,8 +11847,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -5864,7 +11873,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -5900,6 +11915,8 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. :attr str message_to_user: The message to display to the user when initiating a channel transfer. :attr ChannelTransferInfo transfer_info: Information used by an integration to @@ -5922,6 +11939,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an @@ -5964,8 +11983,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -5983,9 +12002,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6110,8 +12138,8 @@ def from_dict( args['topic'] = _dict.get('topic') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -6130,16 +12158,31 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6165,6 +12208,72 @@ def __ne__( return not self == other +class RuntimeResponseGenericRuntimeResponseTypeDate(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeDate. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + """ + + def __init__(self, response_type: str) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeDate': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeDate JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeDate object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeDate') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeDate') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. @@ -6243,8 +12352,8 @@ def from_dict( args['image_url'] = _dict.get('image_url') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -6267,7 +12376,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6367,8 +12482,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'alt_text' in _dict: args['alt_text'] = _dict.get('alt_text') @@ -6391,7 +12506,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -6492,8 +12613,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) + for v in _dict.get('options') ] else: raise ValueError( @@ -6501,8 +12622,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -6523,9 +12644,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6621,8 +12754,8 @@ def from_dict( args['typing'] = _dict.get('typing') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -6641,7 +12774,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6736,7 +12875,7 @@ def from_dict( ) if 'primary_results' in _dict: args['primary_results'] = [ - SearchResult.from_dict(x) for x in _dict.get('primary_results') + SearchResult.from_dict(v) for v in _dict.get('primary_results') ] else: raise ValueError( @@ -6744,8 +12883,8 @@ def from_dict( ) if 'additional_results' in _dict: args['additional_results'] = [ - SearchResult.from_dict(x) - for x in _dict.get('additional_results') + SearchResult.from_dict(v) + for v in _dict.get('additional_results') ] else: raise ValueError( @@ -6753,8 +12892,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -6772,17 +12911,31 @@ def to_dict(self) -> Dict: _dict['header'] = self.header if hasattr(self, 'primary_results') and self.primary_results is not None: - _dict['primary_results'] = [ - x.to_dict() for x in self.primary_results - ] + primary_results_list = [] + for v in self.primary_results: + if isinstance(v, dict): + primary_results_list.append(v) + else: + primary_results_list.append(v.to_dict()) + _dict['primary_results'] = primary_results_list if hasattr( self, 'additional_results') and self.additional_results is not None: - _dict['additional_results'] = [ - x.to_dict() for x in self.additional_results - ] + additional_results_list = [] + for v in self.additional_results: + if isinstance(v, dict): + additional_results_list.append(v) + else: + additional_results_list.append(v.to_dict()) + _dict['additional_results'] = additional_results_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6871,7 +13024,7 @@ def from_dict( ) if 'suggestions' in _dict: args['suggestions'] = [ - DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') ] else: raise ValueError( @@ -6879,8 +13032,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -6897,9 +13050,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + suggestions_list = [] + for v in self.suggestions: + if isinstance(v, dict): + suggestions_list.append(v) + else: + suggestions_list.append(v.to_dict()) + _dict['suggestions'] = suggestions_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -6980,8 +13145,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -6998,7 +13163,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -7080,8 +13251,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -7098,7 +13269,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -7138,7 +13315,7 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -7150,7 +13327,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -7167,7 +13344,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -7204,8 +13381,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -7230,7 +13407,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 08411eb79..28c723130 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ -IBM Watson™ Discovery is a cognitive search and content analytics engine that you +IBM Watson™ Discovery v1 is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of @@ -115,15 +115,22 @@ def create_environment(self, operation_id='create_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name, 'description': description, 'size': size} + data = { + 'name': name, + 'description': description, + 'size': size, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/environments' @@ -157,10 +164,14 @@ def list_environments(self, operation_id='list_environments') headers.update(sdk_headers) - params = {'version': self.version, 'name': name} + params = { + 'version': self.version, + 'name': name, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/environments' @@ -183,7 +194,7 @@ def get_environment(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -191,10 +202,13 @@ def get_environment(self, environment_id: str, operation_id='get_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -232,7 +246,7 @@ def update_environment(self, :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -240,15 +254,22 @@ def update_environment(self, operation_id='update_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name, 'description': description, 'size': size} + data = { + 'name': name, + 'description': description, + 'size': size, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -275,7 +296,7 @@ def delete_environment(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteEnvironmentResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -283,10 +304,13 @@ def delete_environment(self, environment_id: str, operation_id='delete_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -317,7 +341,7 @@ def list_fields(self, environment_id: str, collection_ids: List[str], :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') @@ -329,11 +353,12 @@ def list_fields(self, environment_id: str, collection_ids: List[str], params = { 'version': self.version, - 'collection_ids': convert_list(collection_ids) + 'collection_ids': convert_list(collection_ids), } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -396,7 +421,7 @@ def create_configuration( :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if name is None: raise ValueError('name must be provided') @@ -414,7 +439,9 @@ def create_configuration( operation_id='create_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, @@ -422,7 +449,7 @@ def create_configuration( 'conversions': conversions, 'enrichments': enrichments, 'normalizations': normalizations, - 'source': source + 'source': source, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -430,6 +457,7 @@ def create_configuration( if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -463,7 +491,7 @@ def list_configurations(self, :rtype: DetailedResponse with `dict` result representing a `ListConfigurationsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -471,10 +499,14 @@ def list_configurations(self, operation_id='list_configurations') headers.update(sdk_headers) - params = {'version': self.version, 'name': name} + params = { + 'version': self.version, + 'name': name, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -502,9 +534,9 @@ def get_configuration(self, environment_id: str, configuration_id: str, :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if configuration_id is None: + if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -512,10 +544,13 @@ def get_configuration(self, environment_id: str, configuration_id: str, operation_id='get_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'configuration_id'] @@ -576,9 +611,9 @@ def update_configuration( :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if configuration_id is None: + if not configuration_id: raise ValueError('configuration_id must be provided') if name is None: raise ValueError('name must be provided') @@ -596,7 +631,9 @@ def update_configuration( operation_id='update_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, @@ -604,7 +641,7 @@ def update_configuration( 'conversions': conversions, 'enrichments': enrichments, 'normalizations': normalizations, - 'source': source + 'source': source, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -612,6 +649,7 @@ def update_configuration( if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'configuration_id'] @@ -648,9 +686,9 @@ def delete_configuration(self, environment_id: str, configuration_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteConfigurationResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if configuration_id is None: + if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -658,10 +696,13 @@ def delete_configuration(self, environment_id: str, configuration_id: str, operation_id='delete_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'configuration_id'] @@ -705,7 +746,7 @@ def create_collection(self, :rtype: DetailedResponse with `dict` result representing a `Collection` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if name is None: raise ValueError('name must be provided') @@ -715,13 +756,15 @@ def create_collection(self, operation_id='create_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, 'description': description, 'configuration_id': configuration_id, - 'language': language + 'language': language, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -729,6 +772,7 @@ def create_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -762,7 +806,7 @@ def list_collections(self, :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -770,10 +814,14 @@ def list_collections(self, operation_id='list_collections') headers.update(sdk_headers) - params = {'version': self.version, 'name': name} + params = { + 'version': self.version, + 'name': name, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -801,9 +849,9 @@ def get_collection(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Collection` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -811,10 +859,13 @@ def get_collection(self, environment_id: str, collection_id: str, operation_id='get_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -852,9 +903,9 @@ def update_collection(self, :rtype: DetailedResponse with `dict` result representing a `Collection` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if name is None: raise ValueError('name must be provided') @@ -864,12 +915,14 @@ def update_collection(self, operation_id='update_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, 'description': description, - 'configuration_id': configuration_id + 'configuration_id': configuration_id, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -877,6 +930,7 @@ def update_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -905,9 +959,9 @@ def delete_collection(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteCollectionResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -915,10 +969,13 @@ def delete_collection(self, environment_id: str, collection_id: str, operation_id='delete_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -948,9 +1005,9 @@ def list_collection_fields(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -958,10 +1015,13 @@ def list_collection_fields(self, environment_id: str, collection_id: str, operation_id='list_collection_fields') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -996,9 +1056,9 @@ def list_expansions(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1006,10 +1066,13 @@ def list_expansions(self, environment_id: str, collection_id: str, operation_id='list_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1055,9 +1118,9 @@ def create_expansions(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if expansions is None: raise ValueError('expansions must be provided') @@ -1068,15 +1131,20 @@ def create_expansions(self, environment_id: str, collection_id: str, operation_id='create_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'expansions': expansions} + data = { + 'expansions': expansions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1108,9 +1176,9 @@ def delete_expansions(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1118,10 +1186,13 @@ def delete_expansions(self, environment_id: str, collection_id: str, operation_id='delete_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -1152,9 +1223,9 @@ def get_tokenization_dictionary_status(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -1163,10 +1234,13 @@ def get_tokenization_dictionary_status(self, environment_id: str, operation_id='get_tokenization_dictionary_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1205,9 +1279,9 @@ def create_tokenization_dictionary( :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if tokenization_rules is not None: tokenization_rules = [convert_model(x) for x in tokenization_rules] @@ -1218,15 +1292,20 @@ def create_tokenization_dictionary( operation_id='create_tokenization_dictionary') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'tokenization_rules': tokenization_rules} + data = { + 'tokenization_rules': tokenization_rules, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1258,9 +1337,9 @@ def delete_tokenization_dictionary(self, environment_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -1269,10 +1348,13 @@ def delete_tokenization_dictionary(self, environment_id: str, operation_id='delete_tokenization_dictionary') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -1301,9 +1383,9 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1311,10 +1393,13 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, operation_id='get_stopword_list_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1351,9 +1436,9 @@ def create_stopword_list(self, :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if stopword_file is None: raise ValueError('stopword_file must be provided') @@ -1363,7 +1448,9 @@ def create_stopword_list(self, operation_id='create_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if not stopword_filename and hasattr(stopword_file, 'name'): @@ -1375,6 +1462,7 @@ def create_stopword_list(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1406,9 +1494,9 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1416,10 +1504,13 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, operation_id='delete_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -1489,9 +1580,9 @@ def add_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1499,7 +1590,9 @@ def add_document(self, operation_id='add_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -1514,6 +1607,7 @@ def add_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1548,11 +1642,11 @@ def get_document_status(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1560,10 +1654,13 @@ def get_document_status(self, environment_id: str, collection_id: str, operation_id='get_document_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'document_id'] @@ -1617,11 +1714,11 @@ def update_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1629,7 +1726,9 @@ def update_document(self, operation_id='update_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -1644,6 +1743,7 @@ def update_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'document_id'] @@ -1678,11 +1778,11 @@ def delete_document(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1690,10 +1790,13 @@ def delete_document(self, environment_id: str, collection_id: str, operation_id='delete_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'document_id'] @@ -1828,17 +1931,21 @@ def query(self, :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} + headers = { + 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'filter': filter, @@ -1860,7 +1967,7 @@ def query(self, 'similar.document_ids': similar_document_ids, 'similar.fields': similar_fields, 'bias': bias, - 'spelling_suggestions': spelling_suggestions + 'spelling_suggestions': spelling_suggestions, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1868,6 +1975,7 @@ def query(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1976,9 +2084,9 @@ def query_notices(self, :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2004,11 +2112,12 @@ def query_notices(self, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields) + 'similar.fields': convert_list(similar_fields), } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2132,17 +2241,21 @@ def federated_query(self, :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} + headers = { + 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='federated_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'collection_ids': collection_ids, @@ -2164,7 +2277,7 @@ def federated_query(self, 'similar': similar, 'similar.document_ids': similar_document_ids, 'similar.fields': similar_fields, - 'bias': bias + 'bias': bias, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2172,6 +2285,7 @@ def federated_query(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -2267,7 +2381,7 @@ def federated_query_notices(self, :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') @@ -2292,11 +2406,12 @@ def federated_query_notices(self, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields) + 'similar.fields': convert_list(similar_fields), } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -2340,11 +2455,11 @@ def get_autocompletion(self, :rtype: DetailedResponse with `dict` result representing a `Completions` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if prefix is None: + if not prefix: raise ValueError('prefix must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2356,11 +2471,12 @@ def get_autocompletion(self, 'version': self.version, 'prefix': prefix, 'field': field, - 'count': count + 'count': count, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2394,9 +2510,9 @@ def list_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingDataSet` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2404,10 +2520,13 @@ def list_training_data(self, environment_id: str, collection_id: str, operation_id='list_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2450,9 +2569,9 @@ def add_training_data(self, :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if examples is not None: examples = [convert_model(x) for x in examples] @@ -2462,12 +2581,14 @@ def add_training_data(self, operation_id='add_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'natural_language_query': natural_language_query, 'filter': filter, - 'examples': examples + 'examples': examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2475,6 +2596,7 @@ def add_training_data(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2505,9 +2627,9 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2515,10 +2637,13 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, operation_id='delete_all_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -2549,11 +2674,11 @@ def get_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2561,10 +2686,13 @@ def get_training_data(self, environment_id: str, collection_id: str, operation_id='get_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'query_id'] @@ -2597,11 +2725,11 @@ def delete_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2609,10 +2737,13 @@ def delete_training_data(self, environment_id: str, collection_id: str, operation_id='delete_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id', 'query_id'] path_param_values = self.encode_path_vars(environment_id, collection_id, @@ -2643,11 +2774,11 @@ def list_training_examples(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingExampleList` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2655,10 +2786,13 @@ def list_training_examples(self, environment_id: str, collection_id: str, operation_id='list_training_examples') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'query_id'] @@ -2702,11 +2836,11 @@ def create_training_example(self, :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2714,12 +2848,14 @@ def create_training_example(self, operation_id='create_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'document_id': document_id, 'cross_reference': cross_reference, - 'relevance': relevance + 'relevance': relevance, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2727,6 +2863,7 @@ def create_training_example(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'query_id'] @@ -2761,13 +2898,13 @@ def delete_training_example(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') - if example_id is None: + if not example_id: raise ValueError('example_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2775,10 +2912,13 @@ def delete_training_example(self, environment_id: str, collection_id: str, operation_id='delete_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = [ 'environment_id', 'collection_id', 'query_id', 'example_id' @@ -2821,13 +2961,13 @@ def update_training_example(self, :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') - if example_id is None: + if not example_id: raise ValueError('example_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2835,15 +2975,21 @@ def update_training_example(self, operation_id='update_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'cross_reference': cross_reference, 'relevance': relevance} + data = { + 'cross_reference': cross_reference, + 'relevance': relevance, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = [ @@ -2880,13 +3026,13 @@ def get_training_example(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') - if example_id is None: + if not example_id: raise ValueError('example_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2894,10 +3040,13 @@ def get_training_example(self, environment_id: str, collection_id: str, operation_id='get_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = [ @@ -2938,7 +3087,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2946,10 +3095,14 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' request = self.prepare_request(method='DELETE', @@ -2991,15 +3144,21 @@ def create_event(self, type: str, data: 'EventData', operation_id='create_event') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'type': type, 'data': data} + data = { + 'type': type, + 'data': data, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/events' @@ -3060,11 +3219,12 @@ def query_log(self, 'query': query, 'count': count, 'offset': offset, - 'sort': convert_list(sort) + 'sort': convert_list(sort), } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/logs' @@ -3109,11 +3269,12 @@ def get_metrics_query(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries' @@ -3159,11 +3320,12 @@ def get_metrics_query_event(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_event' @@ -3209,11 +3371,12 @@ def get_metrics_query_no_results(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_no_search_results' @@ -3259,11 +3422,12 @@ def get_metrics_event_rate(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/event_rate' @@ -3301,10 +3465,14 @@ def get_metrics_query_token_event(self, operation_id='get_metrics_query_token_event') headers.update(sdk_headers) - params = {'version': self.version, 'count': count} + params = { + 'version': self.version, + 'count': count, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/top_query_tokens_with_event_rate' @@ -3335,7 +3503,7 @@ def list_credentials(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `CredentialsList` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3343,10 +3511,13 @@ def list_credentials(self, environment_id: str, operation_id='list_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3399,7 +3570,7 @@ def create_credentials(self, :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if credential_details is not None: credential_details = convert_model(credential_details) @@ -3411,12 +3582,14 @@ def create_credentials(self, operation_id='create_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'source_type': source_type, 'credential_details': credential_details, - 'status': status + 'status': status, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3424,6 +3597,7 @@ def create_credentials(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3457,9 +3631,9 @@ def get_credentials(self, environment_id: str, credential_id: str, :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if credential_id is None: + if not credential_id: raise ValueError('credential_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3467,10 +3641,13 @@ def get_credentials(self, environment_id: str, credential_id: str, operation_id='get_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'credential_id'] @@ -3525,9 +3702,9 @@ def update_credentials(self, :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if credential_id is None: + if not credential_id: raise ValueError('credential_id must be provided') if credential_details is not None: credential_details = convert_model(credential_details) @@ -3539,12 +3716,14 @@ def update_credentials(self, operation_id='update_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'source_type': source_type, 'credential_details': credential_details, - 'status': status + 'status': status, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3552,6 +3731,7 @@ def update_credentials(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'credential_id'] @@ -3583,9 +3763,9 @@ def delete_credentials(self, environment_id: str, credential_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteCredentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if credential_id is None: + if not credential_id: raise ValueError('credential_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3593,10 +3773,13 @@ def delete_credentials(self, environment_id: str, credential_id: str, operation_id='delete_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'credential_id'] @@ -3628,7 +3811,7 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `GatewayList` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3636,10 +3819,13 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: operation_id='list_gateways') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3672,7 +3858,7 @@ def create_gateway(self, :rtype: DetailedResponse with `dict` result representing a `Gateway` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3680,15 +3866,20 @@ def create_gateway(self, operation_id='create_gateway') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name} + data = { + 'name': name, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3719,9 +3910,9 @@ def get_gateway(self, environment_id: str, gateway_id: str, :rtype: DetailedResponse with `dict` result representing a `Gateway` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if gateway_id is None: + if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3729,10 +3920,13 @@ def get_gateway(self, environment_id: str, gateway_id: str, operation_id='get_gateway') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'gateway_id'] @@ -3762,9 +3956,9 @@ def delete_gateway(self, environment_id: str, gateway_id: str, :rtype: DetailedResponse with `dict` result representing a `GatewayDelete` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if gateway_id is None: + if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3772,10 +3966,13 @@ def delete_gateway(self, environment_id: str, gateway_id: str, operation_id='delete_gateway') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'gateway_id'] @@ -4021,19 +4218,35 @@ def to_dict(self) -> Dict: _dict['language'] = self.language if hasattr(self, 'document_counts') and self.document_counts is not None: - _dict['document_counts'] = self.document_counts.to_dict() + if isinstance(self.document_counts, dict): + _dict['document_counts'] = self.document_counts + else: + _dict['document_counts'] = self.document_counts.to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage.to_dict() + if isinstance(self.disk_usage, dict): + _dict['disk_usage'] = self.disk_usage + else: + _dict['disk_usage'] = self.disk_usage.to_dict() if hasattr(self, 'training_status') and self.training_status is not None: - _dict['training_status'] = self.training_status.to_dict() + if isinstance(self.training_status, dict): + _dict['training_status'] = self.training_status + else: + _dict['training_status'] = self.training_status.to_dict() if hasattr(self, 'crawl_status') and self.crawl_status is not None: - _dict['crawl_status'] = self.crawl_status.to_dict() + if isinstance(self.crawl_status, dict): + _dict['crawl_status'] = self.crawl_status + else: + _dict['crawl_status'] = self.crawl_status.to_dict() if hasattr(self, 'smart_document_understanding' ) and self.smart_document_understanding is not None: - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding.to_dict( - ) + if isinstance(self.smart_document_understanding, dict): + _dict[ + 'smart_document_understanding'] = self.smart_document_understanding + else: + _dict[ + 'smart_document_understanding'] = self.smart_document_understanding.to_dict( + ) return _dict def _to_dict(self): @@ -4098,7 +4311,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'source_crawl') and self.source_crawl is not None: - _dict['source_crawl'] = self.source_crawl.to_dict() + if isinstance(self.source_crawl, dict): + _dict['source_crawl'] = self.source_crawl + else: + _dict['source_crawl'] = self.source_crawl.to_dict() return _dict def _to_dict(self): @@ -4377,12 +4593,12 @@ def from_dict(cls, _dict: Dict) -> 'Configuration': _dict.get('conversions')) if 'enrichments' in _dict: args['enrichments'] = [ - Enrichment.from_dict(x) for x in _dict.get('enrichments') + Enrichment.from_dict(v) for v in _dict.get('enrichments') ] if 'normalizations' in _dict: args['normalizations'] = [ - NormalizationOperation.from_dict(x) - for x in _dict.get('normalizations') + NormalizationOperation.from_dict(v) + for v in _dict.get('normalizations') ] if 'source' in _dict: args['source'] = Source.from_dict(_dict.get('source')) @@ -4408,13 +4624,31 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'conversions') and self.conversions is not None: - _dict['conversions'] = self.conversions.to_dict() + if isinstance(self.conversions, dict): + _dict['conversions'] = self.conversions + else: + _dict['conversions'] = self.conversions.to_dict() if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list if hasattr(self, 'normalizations') and self.normalizations is not None: - _dict['normalizations'] = [x.to_dict() for x in self.normalizations] + normalizations_list = [] + for v in self.normalizations: + if isinstance(v, dict): + normalizations_list.append(v) + else: + normalizations_list.append(v.to_dict()) + _dict['normalizations'] = normalizations_list if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -4504,8 +4738,8 @@ def from_dict(cls, _dict: Dict) -> 'Conversions': args['segment'] = SegmentSettings.from_dict(_dict.get('segment')) if 'json_normalizations' in _dict: args['json_normalizations'] = [ - NormalizationOperation.from_dict(x) - for x in _dict.get('json_normalizations') + NormalizationOperation.from_dict(v) + for v in _dict.get('json_normalizations') ] if 'image_text_recognition' in _dict: args['image_text_recognition'] = _dict.get('image_text_recognition') @@ -4520,19 +4754,35 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pdf') and self.pdf is not None: - _dict['pdf'] = self.pdf.to_dict() + if isinstance(self.pdf, dict): + _dict['pdf'] = self.pdf + else: + _dict['pdf'] = self.pdf.to_dict() if hasattr(self, 'word') and self.word is not None: - _dict['word'] = self.word.to_dict() + if isinstance(self.word, dict): + _dict['word'] = self.word + else: + _dict['word'] = self.word.to_dict() if hasattr(self, 'html') and self.html is not None: - _dict['html'] = self.html.to_dict() + if isinstance(self.html, dict): + _dict['html'] = self.html + else: + _dict['html'] = self.html.to_dict() if hasattr(self, 'segment') and self.segment is not None: - _dict['segment'] = self.segment.to_dict() + if isinstance(self.segment, dict): + _dict['segment'] = self.segment + else: + _dict['segment'] = self.segment.to_dict() if hasattr( self, 'json_normalizations') and self.json_normalizations is not None: - _dict['json_normalizations'] = [ - x.to_dict() for x in self.json_normalizations - ] + json_normalizations_list = [] + for v in self.json_normalizations: + if isinstance(v, dict): + json_normalizations_list.append(v) + else: + json_normalizations_list.append(v.to_dict()) + _dict['json_normalizations'] = json_normalizations_list if hasattr(self, 'image_text_recognition' ) and self.image_text_recognition is not None: _dict['image_text_recognition'] = self.image_text_recognition @@ -4596,7 +4846,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'data') and self.data is not None: - _dict['data'] = self.data.to_dict() + if isinstance(self.data, dict): + _dict['data'] = self.data + else: + _dict['data'] = self.data.to_dict() return _dict def _to_dict(self): @@ -5063,9 +5316,15 @@ def to_dict(self) -> Dict: if hasattr( self, 'credential_details') and self.credential_details is not None: - _dict['credential_details'] = self.credential_details.to_dict() + if isinstance(self.credential_details, dict): + _dict['credential_details'] = self.credential_details + else: + _dict['credential_details'] = self.credential_details.to_dict() if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status.to_dict() + if isinstance(self.status, dict): + _dict['status'] = self.status + else: + _dict['status'] = self.status.to_dict() return _dict def _to_dict(self): @@ -5128,7 +5387,7 @@ def from_dict(cls, _dict: Dict) -> 'CredentialsList': args = {} if 'credentials' in _dict: args['credentials'] = [ - Credentials.from_dict(x) for x in _dict.get('credentials') + Credentials.from_dict(v) for v in _dict.get('credentials') ] return cls(**args) @@ -5141,7 +5400,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credentials') and self.credentials is not None: - _dict['credentials'] = [x.to_dict() for x in self.credentials] + credentials_list = [] + for v in self.credentials: + if isinstance(v, dict): + credentials_list.append(v) + else: + credentials_list.append(v.to_dict()) + _dict['credentials'] = credentials_list return _dict def _to_dict(self): @@ -5289,7 +5554,7 @@ def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': ) if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -5307,7 +5572,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -5663,7 +5934,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': args['status'] = _dict.get('status') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -5680,7 +5951,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -5858,7 +6135,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentStatus': args['sha1'] = _dict.get('sha1') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -5888,7 +6165,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 if hasattr(self, 'notices') and getattr(self, 'notices') is not None: - _dict['notices'] = [x.to_dict() for x in getattr(self, 'notices')] + notices_list = [] + for v in getattr(self, 'notices'): + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -6059,7 +6342,10 @@ def to_dict(self) -> Dict: ) and self.ignore_downstream_errors is not None: _dict['ignore_downstream_errors'] = self.ignore_downstream_errors if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -6096,8 +6382,8 @@ class EnrichmentOptions(): (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :attr str model: (optional) The element extraction model to use, which can be - `contract` only. The `elements` enrichment is deprecated. + :attr str model: (optional) Deprecated: The element extraction model to use, + which can be `contract` only. The `elements` enrichment is deprecated. """ def __init__(self, @@ -6116,8 +6402,8 @@ def __init__(self, `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :param str model: (optional) The element extraction model to use, which can - be `contract` only. The `elements` enrichment is deprecated. + :param str model: (optional) Deprecated: The element extraction model to + use, which can be `contract` only. The `elements` enrichment is deprecated. """ self.features = features self.language = language @@ -6145,7 +6431,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'features') and self.features is not None: - _dict['features'] = self.features.to_dict() + if isinstance(self.features, dict): + _dict['features'] = self.features + else: + _dict['features'] = self.features.to_dict() if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'model') and self.model is not None: @@ -6315,9 +6604,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'requested_size') and self.requested_size is not None: _dict['requested_size'] = self.requested_size if hasattr(self, 'index_capacity') and self.index_capacity is not None: - _dict['index_capacity'] = self.index_capacity.to_dict() + if isinstance(self.index_capacity, dict): + _dict['index_capacity'] = self.index_capacity + else: + _dict['index_capacity'] = self.index_capacity.to_dict() if hasattr(self, 'search_status') and self.search_status is not None: - _dict['search_status'] = self.search_status.to_dict() + if isinstance(self.search_status, dict): + _dict['search_status'] = self.search_status + else: + _dict['search_status'] = self.search_status.to_dict() return _dict def _to_dict(self): @@ -6689,7 +6984,7 @@ def from_dict(cls, _dict: Dict) -> 'Expansions': args = {} if 'expansions' in _dict: args['expansions'] = [ - Expansion.from_dict(x) for x in _dict.get('expansions') + Expansion.from_dict(v) for v in _dict.get('expansions') ] else: raise ValueError( @@ -6706,7 +7001,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'expansions') and self.expansions is not None: - _dict['expansions'] = [x.to_dict() for x in self.expansions] + expansions_list = [] + for v in self.expansions: + if isinstance(v, dict): + expansions_list.append(v) + else: + expansions_list.append(v.to_dict()) + _dict['expansions'] = expansions_list return _dict def _to_dict(self): @@ -7092,7 +7393,7 @@ def from_dict(cls, _dict: Dict) -> 'GatewayList': args = {} if 'gateways' in _dict: args['gateways'] = [ - Gateway.from_dict(x) for x in _dict.get('gateways') + Gateway.from_dict(v) for v in _dict.get('gateways') ] return cls(**args) @@ -7105,7 +7406,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'gateways') and self.gateways is not None: - _dict['gateways'] = [x.to_dict() for x in self.gateways] + gateways_list = [] + for v in self.gateways: + if isinstance(v, dict): + gateways_list.append(v) + else: + gateways_list.append(v.to_dict()) + _dict['gateways'] = gateways_list return _dict def _to_dict(self): @@ -7213,10 +7520,16 @@ def to_dict(self) -> Dict: ) and self.exclude_tags_keep_content is not None: _dict['exclude_tags_keep_content'] = self.exclude_tags_keep_content if hasattr(self, 'keep_content') and self.keep_content is not None: - _dict['keep_content'] = self.keep_content.to_dict() + if isinstance(self.keep_content, dict): + _dict['keep_content'] = self.keep_content + else: + _dict['keep_content'] = self.keep_content.to_dict() if hasattr(self, 'exclude_content') and self.exclude_content is not None: - _dict['exclude_content'] = self.exclude_content.to_dict() + if isinstance(self.exclude_content, dict): + _dict['exclude_content'] = self.exclude_content + else: + _dict['exclude_content'] = self.exclude_content.to_dict() if hasattr( self, 'keep_tag_attributes') and self.keep_tag_attributes is not None: @@ -7299,11 +7612,20 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = self.documents.to_dict() + if isinstance(self.documents, dict): + _dict['documents'] = self.documents + else: + _dict['documents'] = self.documents.to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage.to_dict() + if isinstance(self.disk_usage, dict): + _dict['disk_usage'] = self.disk_usage + else: + _dict['disk_usage'] = self.disk_usage.to_dict() if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = self.collections.to_dict() + if isinstance(self.collections, dict): + _dict['collections'] = self.collections + else: + _dict['collections'] = self.collections.to_dict() return _dict def _to_dict(self): @@ -7356,7 +7678,7 @@ def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} if 'fields' in _dict: - args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] + args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] return cls(**args) @classmethod @@ -7368,7 +7690,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x.to_dict() for x in self.fields] + fields_list = [] + for v in self.fields: + if isinstance(v, dict): + fields_list.append(v) + else: + fields_list.append(v.to_dict()) + _dict['fields'] = fields_list return _dict def _to_dict(self): @@ -7413,7 +7741,7 @@ def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': args = {} if 'collections' in _dict: args['collections'] = [ - Collection.from_dict(x) for x in _dict.get('collections') + Collection.from_dict(v) for v in _dict.get('collections') ] return cls(**args) @@ -7426,7 +7754,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] + collections_list = [] + for v in self.collections: + if isinstance(v, dict): + collections_list.append(v) + else: + collections_list.append(v.to_dict()) + _dict['collections'] = collections_list return _dict def _to_dict(self): @@ -7471,7 +7805,7 @@ def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': args = {} if 'configurations' in _dict: args['configurations'] = [ - Configuration.from_dict(x) for x in _dict.get('configurations') + Configuration.from_dict(v) for v in _dict.get('configurations') ] return cls(**args) @@ -7484,7 +7818,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configurations') and self.configurations is not None: - _dict['configurations'] = [x.to_dict() for x in self.configurations] + configurations_list = [] + for v in self.configurations: + if isinstance(v, dict): + configurations_list.append(v) + else: + configurations_list.append(v.to_dict()) + _dict['configurations'] = configurations_list return _dict def _to_dict(self): @@ -7529,7 +7869,7 @@ def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': args = {} if 'environments' in _dict: args['environments'] = [ - Environment.from_dict(x) for x in _dict.get('environments') + Environment.from_dict(v) for v in _dict.get('environments') ] return cls(**args) @@ -7542,7 +7882,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environments') and self.environments is not None: - _dict['environments'] = [x.to_dict() for x in self.environments] + environments_list = [] + for v in self.environments: + if isinstance(v, dict): + environments_list.append(v) + else: + environments_list.append(v.to_dict()) + _dict['environments'] = environments_list return _dict def _to_dict(self): @@ -7595,8 +7941,8 @@ def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - LogQueryResponseResult.from_dict(x) - for x in _dict.get('results') + LogQueryResponseResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -7612,7 +7958,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -7833,7 +8185,10 @@ def to_dict(self) -> Dict: _dict['natural_language_query'] = self.natural_language_query if hasattr(self, 'document_results') and self.document_results is not None: - _dict['document_results'] = self.document_results.to_dict() + if isinstance(self.document_results, dict): + _dict['document_results'] = self.document_results + else: + _dict['document_results'] = self.document_results.to_dict() if hasattr(self, 'created_timestamp') and self.created_timestamp is not None: _dict['created_timestamp'] = datetime_to_string( @@ -7935,8 +8290,8 @@ def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': args = {} if 'results' in _dict: args['results'] = [ - LogQueryResponseResultDocumentsResult.from_dict(x) - for x in _dict.get('results') + LogQueryResponseResultDocumentsResult.from_dict(v) + for v in _dict.get('results') ] if 'count' in _dict: args['count'] = _dict.get('count') @@ -7951,7 +8306,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count return _dict @@ -8115,8 +8476,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricAggregation': args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ - MetricAggregationResult.from_dict(x) - for x in _dict.get('results') + MetricAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -8133,7 +8494,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8270,8 +8637,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricResponse': args = {} if 'aggregations' in _dict: args['aggregations'] = [ - MetricAggregation.from_dict(x) - for x in _dict.get('aggregations') + MetricAggregation.from_dict(v) + for v in _dict.get('aggregations') ] return cls(**args) @@ -8284,7 +8651,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -8339,8 +8712,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ - MetricTokenAggregationResult.from_dict(x) - for x in _dict.get('results') + MetricTokenAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -8355,7 +8728,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8481,8 +8860,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': args = {} if 'aggregations' in _dict: args['aggregations'] = [ - MetricTokenAggregation.from_dict(x) - for x in _dict.get('aggregations') + MetricTokenAggregation.from_dict(v) + for v in _dict.get('aggregations') ] return cls(**args) @@ -8495,7 +8874,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -8864,21 +9249,42 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords.to_dict() + if isinstance(self.keywords, dict): + _dict['keywords'] = self.keywords + else: + _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities.to_dict() + if isinstance(self.entities, dict): + _dict['entities'] = self.entities + else: + _dict['entities'] = self.entities.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = self.categories if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles.to_dict() + if isinstance(self.semantic_roles, dict): + _dict['semantic_roles'] = self.semantic_roles + else: + _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations.to_dict() + if isinstance(self.relations, dict): + _dict['relations'] = self.relations + else: + _dict['relations'] = self.relations.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts.to_dict() + if isinstance(self.concepts, dict): + _dict['concepts'] = self.concepts + else: + _dict['concepts'] = self.concepts.to_dict() return _dict def _to_dict(self): @@ -9488,7 +9894,7 @@ def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': args = {} if 'fonts' in _dict: args['fonts'] = [ - FontSetting.from_dict(x) for x in _dict.get('fonts') + FontSetting.from_dict(v) for v in _dict.get('fonts') ] return cls(**args) @@ -9501,7 +9907,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x.to_dict() for x in self.fonts] + fonts_list = [] + for v in self.fonts: + if isinstance(v, dict): + fonts_list.append(v) + else: + fonts_list.append(v.to_dict()) + _dict['fonts'] = fonts_list return _dict def _to_dict(self): @@ -9558,7 +9970,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading.to_dict() + if isinstance(self.heading, dict): + _dict['heading'] = self.heading + else: + _dict['heading'] = self.heading.to_dict() return _dict def _to_dict(self): @@ -9582,7 +9997,7 @@ def __ne__(self, other: 'PdfSettings') -> bool: class QueryAggregation(): """ - An aggregation produced by Discovery to analyze the input provided. + An aggregation produced by Discovery to analyze the input provided. :attr str type: The type of aggregation command used. For example: term, filter, max, min, etc. @@ -9718,7 +10133,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -9736,7 +10151,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -9807,15 +10228,15 @@ def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryNoticesResult.from_dict(x) for x in _dict.get('results') + QueryNoticesResult.from_dict(v) for v in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] if 'passages' in _dict: args['passages'] = [ - QueryPassages.from_dict(x) for x in _dict.get('passages') + QueryPassages.from_dict(v) for v in _dict.get('passages') ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') @@ -9833,11 +10254,29 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] + passages_list = [] + for v in self.passages: + if isinstance(v, dict): + passages_list.append(v) + else: + passages_list.append(v.to_dict()) + _dict['passages'] = passages_list if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: @@ -9955,7 +10394,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': args['sha1'] = _dict.get('sha1') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -9977,7 +10416,10 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'filename') and self.filename is not None: @@ -9987,13 +10429,18 @@ def to_dict(self) -> Dict: if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list for _key in [ k for k in vars(self).keys() if k not in QueryNoticesResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -10226,15 +10673,15 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryResult.from_dict(x) for x in _dict.get('results') + QueryResult.from_dict(v) for v in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] if 'passages' in _dict: args['passages'] = [ - QueryPassages.from_dict(x) for x in _dict.get('passages') + QueryPassages.from_dict(v) for v in _dict.get('passages') ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') @@ -10259,11 +10706,29 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] + passages_list = [] + for v in self.passages: + if isinstance(v, dict): + passages_list.append(v) + else: + passages_list.append(v.to_dict()) + _dict['passages'] = passages_list if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: @@ -10272,7 +10737,10 @@ def to_dict(self) -> Dict: _dict['session_token'] = self.session_token if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details.to_dict() + if isinstance(self.retrieval_details, dict): + _dict['retrieval_details'] = self.retrieval_details + else: + _dict['retrieval_details'] = self.retrieval_details.to_dict() if hasattr(self, 'suggested_query') and self.suggested_query is not None: _dict['suggested_query'] = self.suggested_query @@ -10371,12 +10839,14 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() for _key in [ k for k in vars(self).keys() if k not in QueryResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -10572,7 +11042,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -10599,7 +11069,13 @@ def to_dict(self) -> Dict: _dict[ 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -10682,7 +11158,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -10702,7 +11178,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -10984,7 +11466,10 @@ def to_dict(self) -> Dict: 'total_documents') and self.total_documents is not None: _dict['total_documents'] = self.total_documents if hasattr(self, 'custom_fields') and self.custom_fields is not None: - _dict['custom_fields'] = self.custom_fields.to_dict() + if isinstance(self.custom_fields, dict): + _dict['custom_fields'] = self.custom_fields + else: + _dict['custom_fields'] = self.custom_fields.to_dict() return _dict def _to_dict(self): @@ -11361,9 +11846,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'schedule') and self.schedule is not None: - _dict['schedule'] = self.schedule.to_dict() + if isinstance(self.schedule, dict): + _dict['schedule'] = self.schedule + else: + _dict['schedule'] = self.schedule.to_dict() if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -11474,24 +11965,24 @@ def from_dict(cls, _dict: Dict) -> 'SourceOptions': args = {} if 'folders' in _dict: args['folders'] = [ - SourceOptionsFolder.from_dict(x) for x in _dict.get('folders') + SourceOptionsFolder.from_dict(v) for v in _dict.get('folders') ] if 'objects' in _dict: args['objects'] = [ - SourceOptionsObject.from_dict(x) for x in _dict.get('objects') + SourceOptionsObject.from_dict(v) for v in _dict.get('objects') ] if 'site_collections' in _dict: args['site_collections'] = [ - SourceOptionsSiteColl.from_dict(x) - for x in _dict.get('site_collections') + SourceOptionsSiteColl.from_dict(v) + for v in _dict.get('site_collections') ] if 'urls' in _dict: args['urls'] = [ - SourceOptionsWebCrawl.from_dict(x) for x in _dict.get('urls') + SourceOptionsWebCrawl.from_dict(v) for v in _dict.get('urls') ] if 'buckets' in _dict: args['buckets'] = [ - SourceOptionsBuckets.from_dict(x) for x in _dict.get('buckets') + SourceOptionsBuckets.from_dict(v) for v in _dict.get('buckets') ] if 'crawl_all_buckets' in _dict: args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') @@ -11506,18 +11997,46 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'folders') and self.folders is not None: - _dict['folders'] = [x.to_dict() for x in self.folders] + folders_list = [] + for v in self.folders: + if isinstance(v, dict): + folders_list.append(v) + else: + folders_list.append(v.to_dict()) + _dict['folders'] = folders_list if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = [x.to_dict() for x in self.objects] + objects_list = [] + for v in self.objects: + if isinstance(v, dict): + objects_list.append(v) + else: + objects_list.append(v.to_dict()) + _dict['objects'] = objects_list if hasattr(self, 'site_collections') and self.site_collections is not None: - _dict['site_collections'] = [ - x.to_dict() for x in self.site_collections - ] + site_collections_list = [] + for v in self.site_collections: + if isinstance(v, dict): + site_collections_list.append(v) + else: + site_collections_list.append(v.to_dict()) + _dict['site_collections'] = site_collections_list if hasattr(self, 'urls') and self.urls is not None: - _dict['urls'] = [x.to_dict() for x in self.urls] + urls_list = [] + for v in self.urls: + if isinstance(v, dict): + urls_list.append(v) + else: + urls_list.append(v.to_dict()) + _dict['urls'] = urls_list if hasattr(self, 'buckets') and self.buckets is not None: - _dict['buckets'] = [x.to_dict() for x in self.buckets] + buckets_list = [] + for v in self.buckets: + if isinstance(v, dict): + buckets_list.append(v) + else: + buckets_list.append(v.to_dict()) + _dict['buckets'] = buckets_list if hasattr(self, 'crawl_all_buckets') and self.crawl_all_buckets is not None: _dict['crawl_all_buckets'] = self.crawl_all_buckets @@ -12465,7 +12984,9 @@ class TrainingDataSet(): training data set. :attr str collection_id: (optional) The collection id associated with this training data set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. + :attr List[TrainingQuery] queries: (optional) Array of training queries. At + least 50 queries are required for training to begin. A maximum of 10,000 queries + are returned. """ def __init__(self, @@ -12481,6 +13002,8 @@ def __init__(self, :param str collection_id: (optional) The collection id associated with this training data set. :param List[TrainingQuery] queries: (optional) Array of training queries. + At least 50 queries are required for training to begin. A maximum of 10,000 + queries are returned. """ self.environment_id = environment_id self.collection_id = collection_id @@ -12496,7 +13019,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': args['collection_id'] = _dict.get('collection_id') if 'queries' in _dict: args['queries'] = [ - TrainingQuery.from_dict(x) for x in _dict.get('queries') + TrainingQuery.from_dict(v) for v in _dict.get('queries') ] return cls(**args) @@ -12513,7 +13036,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x.to_dict() for x in self.queries] + queries_list = [] + for v in self.queries: + if isinstance(v, dict): + queries_list.append(v) + else: + queries_list.append(v.to_dict()) + _dict['queries'] = queries_list return _dict def _to_dict(self): @@ -12634,7 +13163,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': args = {} if 'examples' in _dict: args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') + TrainingExample.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -12647,7 +13176,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -12716,7 +13251,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingQuery': args['filter'] = _dict.get('filter') if 'examples' in _dict: args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') + TrainingExample.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -12736,7 +13271,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'filter') and self.filter is not None: _dict['filter'] = self.filter if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -12935,11 +13476,11 @@ def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': args = {} if 'fonts' in _dict: args['fonts'] = [ - FontSetting.from_dict(x) for x in _dict.get('fonts') + FontSetting.from_dict(v) for v in _dict.get('fonts') ] if 'styles' in _dict: args['styles'] = [ - WordStyle.from_dict(x) for x in _dict.get('styles') + WordStyle.from_dict(v) for v in _dict.get('styles') ] return cls(**args) @@ -12952,9 +13493,21 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x.to_dict() for x in self.fonts] + fonts_list = [] + for v in self.fonts: + if isinstance(v, dict): + fonts_list.append(v) + else: + fonts_list.append(v.to_dict()) + _dict['fonts'] = fonts_list if hasattr(self, 'styles') and self.styles is not None: - _dict['styles'] = [x.to_dict() for x in self.styles] + styles_list = [] + for v in self.styles: + if isinstance(v, dict): + styles_list.append(v) + else: + styles_list.append(v.to_dict()) + _dict['styles'] = styles_list return _dict def _to_dict(self): @@ -13011,7 +13564,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading.to_dict() + if isinstance(self.heading, dict): + _dict['heading'] = self.heading + else: + _dict['heading'] = self.heading.to_dict() return _dict def _to_dict(self): @@ -13284,7 +13840,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -13304,7 +13860,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -13392,8 +13954,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryHistogramAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -13414,7 +13976,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -13495,7 +14063,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -13515,7 +14083,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -13597,8 +14171,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTermAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTermAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -13619,7 +14193,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -13707,8 +14287,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -13729,7 +14309,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -13820,7 +14406,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits.to_dict() + if isinstance(self.hits, dict): + _dict['hits'] = self.hits + else: + _dict['hits'] = self.hits.to_dict() return _dict def _to_dict(self): diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 708007d08..d6af60eb8 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ -IBM Watson™ Discovery is a cognitive search and content analytics engine that you -can add to applications to identify patterns, trends and actionable insights to drive -better decision-making. Securely unify structured and unstructured data with pre-enriched +IBM Watson® Discovery is a cognitive search and content analytics engine that you can +add to applications to identify patterns, trends and actionable insights to drive better +decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of results. @@ -64,7 +64,7 @@ def __init__( Specify dates in YYYY-MM-DD format. The current version is `2020-08-30`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: @@ -79,40 +79,36 @@ def __init__( self.configure_service(service_name) ######################### - # Collections + # Projects ######################### - def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: + def list_projects(self, **kwargs) -> DetailedResponse: """ - List collections. + List projects. - Lists existing collections for the specified project. + Lists existing projects for this instance. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object + :rtype: DetailedResponse with `dict` result representing a `ListProjectsResponse` object """ - if project_id is None: - raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_collections') + operation_id='list_projects') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + url = '/v2/projects' request = self.prepare_request(method='GET', url=url, headers=headers, @@ -121,50 +117,50 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def create_collection(self, - project_id: str, - name: str, - *, - description: str = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def create_project(self, + name: str, + type: str, + *, + default_query_parameters: 'DefaultQueryParams' = None, + **kwargs) -> DetailedResponse: """ - Create a collection. + Create a project. - Create a new collection in the specified project. + Create a new project for this instance. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str language: (optional) The language of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + :param str name: The human readable name of this project. + :param str type: The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* + project and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with + Premium plan managed deployments and installed deployments only. + :param DefaultQueryParams default_query_parameters: (optional) Default + query parameters for this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: - raise ValueError('project_id must be provided') if name is None: raise ValueError('name must be provided') - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] + if type is None: + raise ValueError('type must be provided') + if default_query_parameters is not None: + default_query_parameters = convert_model(default_query_parameters) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_collection') + operation_id='create_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, - 'description': description, - 'language': language, - 'enrichments': enrichments + 'type': type, + 'default_query_parameters': default_query_parameters, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -172,12 +168,10 @@ def create_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + url = '/v2/projects' request = self.prepare_request(method='POST', url=url, headers=headers, @@ -187,42 +181,40 @@ def create_collection(self, response = self.send(request, **kwargs) return response - def get_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_project(self, project_id: str, **kwargs) -> DetailedResponse: """ - Get collection. + Get project. - Get details about the specified collection. + Get details on the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_collection') + operation_id='get_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -231,49 +223,38 @@ def get_collection(self, project_id: str, collection_id: str, response = self.send(request, **kwargs) return response - def update_collection(self, - project_id: str, - collection_id: str, - *, - name: str = None, - description: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def update_project(self, + project_id: str, + *, + name: str = None, + **kwargs) -> DetailedResponse: """ - Update a collection. + Update a project. - Updates the specified collection's name, description, and enrichments. + Update the specified project's name. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param str name: (optional) The name of the collection. - :param str description: (optional) A description of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + :param str name: (optional) The new name to give this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_collection') + operation_id='update_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, - 'description': description, - 'enrichments': enrichments } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -281,13 +262,13 @@ def update_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -297,42 +278,41 @@ def update_collection(self, response = self.send(request, **kwargs) return response - def delete_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: """ - Delete a collection. + Delete a project. - Deletes the specified collection from the project. All documents stored in the - specified collection and not shared is also deleted. + Deletes the specified project. + **Important:** Deleting a project deletes everything that is part of the specified + project, including all collections. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_collection') + operation_id='delete_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -341,197 +321,95 @@ def delete_collection(self, project_id: str, collection_id: str, response = self.send(request, **kwargs) return response - ######################### - # Queries - ######################### - - def query(self, - project_id: str, - *, - collection_ids: List[str] = None, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - spelling_suggestions: bool = None, - table_results: 'QueryLargeTableResults' = None, - suggested_refinements: 'QueryLargeSuggestedRefinements' = None, - passages: 'QueryLargePassages' = None, - **kwargs) -> DetailedResponse: + def list_fields(self, + project_id: str, + *, + collection_ids: List[str] = None, + **kwargs) -> DetailedResponse: """ - Query a project. + List fields. - By using this method, you can construct queries. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). - The default query parameters are defined by the settings for this project, see the - [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-project-defaults) - for an overview of the standard default settings, and see [the Projects API - documentation](#create-project) for details about how to set custom default query - settings. + Gets a list of the unique fields (and their types) stored in the specified + collections. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param List[str] collection_ids: (optional) A comma-separated list of - collection IDs to be queried against. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param List[str] return_: (optional) A list of the fields in the document - hierarchy to return. If this parameter is an empty list, then all fields - are returned. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. - :param str sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param bool highlight: (optional) When `true`, a highlight field is - returned for each result which contains the fields which match the query - with `` tags around the matching query terms. - :param bool spelling_suggestions: (optional) When `true` and the - **natural_language_query** parameter is used, the - **natural_language_query** parameter is spell checked. The most likely - correction is returned in the **suggested_query** field of the response (if - one exists). - :param QueryLargeTableResults table_results: (optional) Configuration for - table retrieval. - :param QueryLargeSuggestedRefinements suggested_refinements: (optional) - Configuration for suggested refinements. Available with Premium plans only. - :param QueryLargePassages passages: (optional) Configuration for passage - retrieval. + :param List[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object + :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if table_results is not None: - table_results = convert_model(table_results) - if suggested_refinements is not None: - suggested_refinements = convert_model(suggested_refinements) - if passages is not None: - passages = convert_model(passages) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='query') + operation_id='list_fields') headers.update(sdk_headers) - params = {'version': self.version} - - data = { - 'collection_ids': collection_ids, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'spelling_suggestions': spelling_suggestions, - 'table_results': table_results, - 'suggested_refinements': suggested_refinements, - 'passages': passages + params = { + 'version': self.version, + 'collection_ids': convert_list(collection_ids), } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/query'.format(**path_param_dict) - request = self.prepare_request(method='POST', + url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def get_autocompletion(self, - project_id: str, - prefix: str, - *, - collection_ids: List[str] = None, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: + ######################### + # Collections + ######################### + + def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: """ - Get Autocomplete Suggestions. + List collections. - Returns completion query suggestions for the specified prefix. + Lists existing collections for the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. - :param List[str] collection_ids: (optional) Comma separated list of the - collection IDs. If this parameter is not specified, all collections in the - project are used. - :param str field: (optional) The field in the result documents that - autocompletion suggestions are identified from. - :param int count: (optional) The number of autocompletion suggestions to - return. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Completions` object + :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if prefix is None: - raise ValueError('prefix must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_autocompletion') + operation_id='list_collections') headers.update(sdk_headers) params = { 'version': self.version, - 'prefix': prefix, - 'collection_ids': convert_list(collection_ids), - 'field': field, - 'count': count } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/autocompletion'.format( - **path_param_dict) + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -540,143 +418,122 @@ def get_autocompletion(self, response = self.send(request, **kwargs) return response - def query_collection_notices(self, - project_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def create_collection(self, + project_id: str, + name: str, + *, + description: str = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None, + **kwargs) -> DetailedResponse: """ - Query collection notices. + Create a collection. - Finds collection-level notices (errors and warnings) that are generated when - documents are ingested. + Create a new collection in the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. For a list + of supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of + enrichments that are available for a project, use the [List + enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about + project default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') + if name is None: + raise ValueError('name must be provided') + if enrichments is not None: + enrichments = [convert_model(x) for x in enrichments] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='query_collection_notices') + operation_id='create_collection') headers.update(sdk_headers) params = { 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'count': count, - 'offset': offset } + data = { + 'name': name, + 'description': description, + 'language': language, + 'enrichments': enrichments, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( - **path_param_dict) - request = self.prepare_request(method='GET', + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - def query_notices(self, - project_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def get_collection(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Query project notices. + Get collection. - Finds project-level notices (errors and warnings). Currently, project-level - notices are generated by relevancy training. + Get details about the specified collection. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. + :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='query_notices') + operation_id='get_collection') headers.update(sdk_headers) params = { 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'count': count, - 'offset': offset } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -685,94 +542,115 @@ def query_notices(self, response = self.send(request, **kwargs) return response - def list_fields(self, - project_id: str, - *, - collection_ids: List[str] = None, - **kwargs) -> DetailedResponse: + def update_collection(self, + project_id: str, + collection_id: str, + *, + name: str = None, + description: str = None, + enrichments: List['CollectionEnrichment'] = None, + **kwargs) -> DetailedResponse: """ - List fields. + Update a collection. - Gets a list of the unique fields (and their types) stored in the the specified - collections. + Updates the specified collection's name, description, and enrichments. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param List[str] collection_ids: (optional) Comma separated list of the - collection IDs. If this parameter is not specified, all collections in the - project are used. + :param str collection_id: The ID of the collection. + :param str name: (optional) The new name of the collection. + :param str description: (optional) The new description of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if enrichments is not None: + enrichments = [convert_model(x) for x in enrichments] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_fields') + operation_id='update_collection') headers.update(sdk_headers) params = { 'version': self.version, - 'collection_ids': convert_list(collection_ids) } + data = { + 'name': name, + 'description': description, + 'enrichments': enrichments, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) - request = self.prepare_request(method='GET', + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - ######################### - # Component settings - ######################### - - def get_component_settings(self, project_id: str, - **kwargs) -> DetailedResponse: + def delete_collection(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - List component settings. + Delete a collection. - Returns default configuration settings for components. + Deletes the specified collection from the project. All documents stored in the + specified collection and not shared is also deleted. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object + :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_component_settings') + operation_id='delete_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/component_settings'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', + request = self.prepare_request(method='DELETE', url=url, headers=headers, params=params) @@ -784,57 +662,163 @@ def get_component_settings(self, project_id: str, # Documents ######################### - def add_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def list_documents(self, + project_id: str, + collection_id: str, + *, + count: int = None, + status: str = None, + has_notices: bool = None, + is_parent: bool = None, + parent_document_id: str = None, + sha256: str = None, + **kwargs) -> DetailedResponse: """ - Add a document. + List documents. - Add a document to a collection with optional metadata. - Returns immediately after the system has accepted the document for processing. - * The user must provide document content, metadata, or both. If the request is - missing both document content and metadata, it is rejected. - * You can set the **Content-Type** parameter on the **file** part to indicate - the media type of the document. If the **Content-Type** parameter is missing or is - one of the generic media types (for example, `application/octet-stream`), then the + Lists the documents in the specified collection. The list includes only the + document ID of each document and returns information for up to 10,000 documents. + **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and + later installed instances and from Plus and Enterprise plan IBM Cloud-managed + instances. It is not currently available from Premium plan instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. + :param int count: (optional) The maximum number of documents to return. Up + to 1,000 documents are returned by default. The maximum number allowed is + 10,000. + :param str status: (optional) Filters the documents to include only + documents with the specified ingestion status. The options include: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because + of an error. + * `pending`: The document is uploaded, but the ingestion process is not + started. + * `processing`: Ingestion is in progress. + You can specify one status value or add a comma-separated list of more than + one status value. For example, `available,failed`. + :param bool has_notices: (optional) If set to `true`, only documents that + have notices, meaning documents for which warnings or errors were generated + during the ingestion, are returned. If set to `false`, only documents that + don't have notices are returned. If unspecified, no filter based on notices + is applied. + Notice details are not available in the result, but you can use the [Query + collection notices](#querycollectionnotices) method to find details by + adding the parameter `query=notices.document_id:{document-id}`. + :param bool is_parent: (optional) If set to `true`, only parent documents, + meaning documents that were split during the ingestion process and resulted + in two or more child documents, are returned. If set to `false`, only child + documents are returned. If unspecified, no filter based on the parent or + child relationship is applied. + CSV files, for example, are split into separate documents per line and JSON + files are split into separate documents per object. + :param str parent_document_id: (optional) Filters the documents to include + only child documents that were generated when the specified parent document + was processed. + :param str sha256: (optional) Filters the documents to include only + documents with the specified SHA-256 hash. Format the hash as a hexadecimal + string. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListDocumentsResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_documents') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'count': count, + 'status': status, + 'has_notices': has_notices, + 'is_parent': is_parent, + 'parent_document_id': parent_document_id, + 'sha256': sha256, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def add_document(self, + project_id: str, + collection_id: str, + *, + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + x_watson_discovery_force: bool = None, + **kwargs) -> DetailedResponse: + """ + Add a document. + + Add a document to a collection with optional metadata. + Returns immediately after the system has accepted the document for processing. + Use this method to upload a file to the collection. You cannot use this method to + crawl an external data source. + * For a list of supported file types, see the [product + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + * You must provide document content, metadata, or both. If the request is missing + both document content and metadata, it is rejected. + * You can set the **Content-Type** parameter on the **file** part to indicate + the media type of the document. If the **Content-Type** parameter is missing or is + one of the generic media types (for example, `application/octet-stream`), then the service attempts to automatically detect the document's media type. - * The following field names are reserved and are filtered out if present after - normalization: `id`, `score`, `highlight`, and any field with the prefix of: `_`, - `+`, or `-` - * Fields with empty name values after normalization are filtered out before - indexing. - * Fields that contain the following characters after normalization are filtered - out before indexing: `#` and `,` - If the document is uploaded to a collection that shares its data with another + * If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. - **Note:** You can assign an ID to a document that you add by appending the ID to - the endpoint + * In curl requests only, you can assign an ID to a document that you add by + appending the ID to the endpoint (`/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}`). If a document already exists with the specified ID, it is replaced. - **Note:** This operation works with a file upload collection. It cannot be used to - modify a collection that crawls an external data source. + For more information about how certain file types and field names are handled when + a file is added to a collection, see the [product + documentation](/docs/discovery-data?topic=discovery-data-index-overview#field-name-limits). :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + :param BinaryIO file: (optional) When adding a document, the content of the + document to ingest. For maximum supported file size limits, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + When analyzing a document, the content of the document to analyze but not + ingest. Only the `application/json` content type is supported currently. + For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is shared with other collections. @@ -843,17 +827,21 @@ def add_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='add_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -868,6 +856,7 @@ def add_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id'] @@ -884,6 +873,61 @@ def add_document(self, response = self.send(request, **kwargs) return response + def get_document(self, project_id: str, collection_id: str, + document_id: str, **kwargs) -> DetailedResponse: + """ + Get document details. + + Get details about a specific document, whether the document is added by uploading + a file or by crawling an external data source. + **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and + later installed instances and from Plus and Enterprise plan IBM Cloud-managed + instances. It is not currently available from Premium plan instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. + :param str document_id: The ID of the document. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentDetails` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not document_id: + raise ValueError('document_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + def update_document(self, project_id: str, collection_id: str, @@ -898,33 +942,42 @@ def update_document(self, """ Update a document. - Replace an existing document or add a document with a specified **document_id**. + Replace an existing document or add a document with a specified document ID. Starts ingesting a document with optional metadata. + Use this method to upload a file to a collection. You cannot use this method to + crawl an external data source. If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. - **Note:** When uploading a new document with this method it automatically replaces - any document stored with the same **document_id** if it exists. - **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that connects to an external - source such as Microsoft SharePoint. - **Note:** If an uploaded document is segmented, all segments are overwritten, even - if the updated version of the document has fewer segments. + **Notes:** + * Uploading a new document with this method automatically replaces any existing + document stored with the same document ID. + * If an uploaded document is split into child documents during ingestion, all + existing child documents are overwritten, even if the updated version of the + document has fewer child documents. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + :param BinaryIO file: (optional) When adding a document, the content of the + document to ingest. For maximum supported file size limits, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + When analyzing a document, the content of the document to analyze but not + ingest. Only the `application/json` content type is supported currently. + For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is shared with other collections. @@ -933,19 +986,23 @@ def update_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='update_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -960,6 +1017,7 @@ def update_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id', 'document_id'] @@ -987,14 +1045,17 @@ def delete_document(self, """ Delete a document. - If the given document ID is invalid, or if the document is not found, then the a - success response is returned (HTTP status code `200`) with the status set to - 'deleted'. - **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that connects to an external - source such as Microsoft SharePoint. - **Note:** Segments of an uploaded document cannot be deleted individually. Delete - all segments by deleting using the `parent_document_id` of a segment result. + Deletes the document with the document ID that you specify from the collection. + Removes uploaded documents from the collection permanently. If you delete a + document that was added by crawling an external data source, the document will be + added again with the next scheduled crawl of the data source. The delete function + removes the document from the collection, not from the external data source. + **Note:** Files such as CSV or JSON files generate subdocuments when they are + added to a collection. If you delete a subdocument, and then repeat the action + that created it, the deleted document is added back in to your collection. To + remove subdocuments that are generated by an uploaded file, delete the original + document instead. You can get the document ID of the original document from the + `parent_document_id` of the subdocument result. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -1008,22 +1069,27 @@ def delete_document(self, :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='delete_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id', 'document_id'] @@ -1041,83 +1107,225 @@ def delete_document(self, return response ######################### - # Training data + # Queries ######################### - def list_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def query(self, + project_id: str, + *, + collection_ids: List[str] = None, + filter: str = None, + query: str = None, + natural_language_query: str = None, + aggregation: str = None, + count: int = None, + return_: List[str] = None, + offset: int = None, + sort: str = None, + highlight: bool = None, + spelling_suggestions: bool = None, + table_results: 'QueryLargeTableResults' = None, + suggested_refinements: 'QueryLargeSuggestedRefinements' = None, + passages: 'QueryLargePassages' = None, + similar: 'QueryLargeSimilar' = None, + **kwargs) -> DetailedResponse: """ - List training queries. + Query a project. - List the training queries for the specified project. + Search your data by submitting queries that are written in natural language or + formatted in the Discovery Query Language. For more information, see the + [Discovery + documentation](/docs/discovery-data?topic=discovery-data-query-concepts). The + default query parameters differ by project type. For more information about the + project default settings, see the [Discovery + documentation](/docs/discovery-data?topic=discovery-data-query-defaults). See [the + Projects API documentation](#create-project) for details about how to set custom + default query settings. + The length of the UTF-8 encoding of the POST body cannot exceed 10,000 bytes, + which is roughly equivalent to 10,000 characters in English. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param List[str] collection_ids: (optional) A comma-separated list of + collection IDs to be queried against. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the **aggregation**, **query**, or + **natural_language_query** parameters, the **filter** parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. Use a query search when you want to find the most + relevant search results. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using training data and natural language + understanding. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For more information + about the supported types of aggregations, see the [Discovery + documentation](/docs/discovery-data?topic=discovery-data-query-aggregations). + :param int count: (optional) Number of results to return. + :param List[str] return_: (optional) A list of the fields in the document + hierarchy to return. You can specify both root-level (`text`) and nested + (`extracted_metadata.filename`) fields. If this parameter is an empty list, + then all fields are returned. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. + :param str sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. + :param bool highlight: (optional) When `true`, a highlight field is + returned for each result that contains fields that match the query. The + matching query terms are emphasized with surrounding `` tags. This + parameter is ignored if **passages.enabled** and **passages.per_document** + are `true`, in which case passages are returned for each document instead + of highlights. + :param bool spelling_suggestions: (optional) When `true` and the + **natural_language_query** parameter is used, the + **natural_language_query** parameter is spell checked. The most likely + correction is returned in the **suggested_query** field of the response (if + one exists). + :param QueryLargeTableResults table_results: (optional) Configuration for + table retrieval. + :param QueryLargeSuggestedRefinements suggested_refinements: (optional) + Configuration for suggested refinements. + **Note**: The **suggested_refinements** parameter that identified dynamic + facets from the data is deprecated. + :param QueryLargePassages passages: (optional) Configuration for passage + retrieval. + :param QueryLargeSimilar similar: (optional) Finds results from documents + that are similar to documents of interest. Use this parameter to add a + *More like these* function to your search. You can include this parameter + with or without a **query**, **filter** or **natural_language_query** + parameter. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object + :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if table_results is not None: + table_results = convert_model(table_results) + if suggested_refinements is not None: + suggested_refinements = convert_model(suggested_refinements) + if passages is not None: + passages = convert_model(passages) + if similar is not None: + similar = convert_model(similar) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_training_queries') + operation_id='query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } + + data = { + 'collection_ids': collection_ids, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'aggregation': aggregation, + 'count': count, + 'return': return_, + 'offset': offset, + 'sort': sort, + 'highlight': highlight, + 'spelling_suggestions': spelling_suggestions, + 'table_results': table_results, + 'suggested_refinements': suggested_refinements, + 'passages': passages, + 'similar': similar, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( - **path_param_dict) - request = self.prepare_request(method='GET', + url = '/v2/projects/{project_id}/query'.format(**path_param_dict) + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - def delete_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def get_autocompletion(self, + project_id: str, + prefix: str, + *, + collection_ids: List[str] = None, + field: str = None, + count: int = None, + **kwargs) -> DetailedResponse: """ - Delete training queries. + Get Autocomplete Suggestions. - Removes all training queries for the specified project. + Returns completion query suggestions for the specified prefix. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str prefix: The prefix to use for autocompletion. For example, the + prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. + :param List[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. + :param str field: (optional) The field in the result documents that + autocompletion suggestions are identified from. + :param int count: (optional) The number of autocompletion suggestions to + return. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Completions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not prefix: + raise ValueError('prefix must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_training_queries') + operation_id='get_autocompletion') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'prefix': prefix, + 'collection_ids': convert_list(collection_ids), + 'field': field, + 'count': count, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( + url = '/v2/projects/{project_id}/autocompletion'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', + request = self.prepare_request(method='GET', url=url, headers=headers, params=params) @@ -1125,110 +1333,157 @@ def delete_training_queries(self, project_id: str, response = self.send(request, **kwargs) return response - def create_training_query(self, - project_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: - """ - Create training query. - - Add a query to the training data for this project. The query can contain a filter - and natural language query. - - :param str project_id: The ID of the project. This information can be found + def query_collection_notices(self, + project_id: str, + collection_id: str, + *, + filter: str = None, + query: str = None, + natural_language_query: str = None, + count: int = None, + offset: int = None, + **kwargs) -> DetailedResponse: + """ + Query collection notices. + + Finds collection-level notices (errors and warnings) that are generated when + documents are ingested. + + :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str natural_language_query: The natural text query for the training - query. - :param List[TrainingExample] examples: Array of training examples. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + :param str collection_id: The ID of the collection. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the `aggregation`, `query`, or + `natural_language_query` parameters, the `filter` parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using training data and natural language + understanding. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is + **10,000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if natural_language_query is None: - raise ValueError('natural_language_query must be provided') - if examples is None: - raise ValueError('examples must be provided') - examples = [convert_model(x) for x in examples] + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_training_query') + operation_id='query_collection_notices') headers.update(sdk_headers) - params = {'version': self.version} - - data = { + params = { + 'version': self.version, + 'filter': filter, + 'query': query, 'natural_language_query': natural_language_query, - 'examples': examples, - 'filter': filter + 'count': count, + 'offset': offset, } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def get_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: + def query_notices(self, + project_id: str, + *, + filter: str = None, + query: str = None, + natural_language_query: str = None, + count: int = None, + offset: int = None, + **kwargs) -> DetailedResponse: """ - Get a training data query. + Query project notices. - Get details for a specific training data query, including the query string and all - examples. + Finds project-level notices (errors and warnings). Currently, project-level + notices are generated by relevancy training. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the `aggregation`, `query`, or + `natural_language_query` parameters, the `filter` parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using training data and natural language + understanding. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is + **10,000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_training_query') + operation_id='query_notices') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'count': count, + 'offset': offset, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1237,238 +1492,216 @@ def get_training_query(self, project_id: str, query_id: str, response = self.send(request, **kwargs) return response - def update_training_query(self, - project_id: str, - query_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + ######################### + # Query modifications + ######################### + + def get_stopword_list(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Update a training query. + Get a custom stop words list. - Updates an existing training query and it's examples. + Returns the custom stop words list that is used by the collection. For information + about the default stop words lists that are applied to queries, see [the product + documentation](/docs/discovery-data?topic=discovery-data-stopwords). :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. - :param str natural_language_query: The natural text query for the training - query. - :param List[TrainingExample] examples: Array of training examples. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - if natural_language_query is None: - raise ValueError('natural_language_query must be provided') - if examples is None: - raise ValueError('examples must be provided') - examples = [convert_model(x) for x in examples] + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_training_query') + operation_id='get_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} - - data = { - 'natural_language_query': natural_language_query, - 'examples': examples, - 'filter': filter + params = { + 'version': self.version, } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def delete_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a training data query. - - Removes details from a training data query, including the query string and all - examples. + def create_stopword_list(self, + project_id: str, + collection_id: str, + *, + stopwords: List[str] = None, + **kwargs) -> DetailedResponse: + """ + Create a custom stop words list. + + Adds a list of custom stop words. Stop words are words that you want the service + to ignore when they occur in a query because they're not useful in distinguishing + the semantic meaning of the query. The stop words list cannot contain more than 1 + million characters. + A default stop words list is used by all collections. The default list is applied + both at indexing time and at query time. A custom stop words list that you add is + used at query time only. + The custom stop words list augments the default stop words list; you cannot remove + stop words. For information about the default stop words lists per language, see + [the product documentation](/docs/discovery-data?topic=discovery-data-stopwords). :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. + :param str collection_id: The ID of the collection. + :param List[str] stopwords: (optional) List of stop words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_training_query') + operation_id='create_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } + + data = { + 'stopwords': stopwords, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - ######################### - # analyze - ######################### - - def analyze_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def delete_stopword_list(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Analyze a Document. + Delete a custom stop words list. - Process a document and return it for realtime use. Supports JSON files only. - The document is processed according to the collection's configuration settings but - is not stored in the collection. - **Note:** This method is supported on installed instances of Discovery only. + Deletes a custom stop words list to stop using it in queries against the + collection. After a custom stop words list is deleted, the default stop words list + is used. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object + :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='analyze_document') + operation_id='delete_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] path_param_keys = ['project_id', 'collection_id'] path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - files=form_data) + params=params) response = self.send(request, **kwargs) return response - ######################### - # enrichments - ######################### - - def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: + def list_expansions(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - List Enrichments. + Get the expansion list. - Lists the enrichments available to this project. The *Part of Speech* and - *Sentiment of Phrases* enrichments might be listed, but are reserved for internal - use only. + Returns the current expansion list for the specified collection. If an expansion + list is not specified, an empty expansions array is returned. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichments` object + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_enrichments') + operation_id='list_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1477,99 +1710,122 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def create_enrichment(self, - project_id: str, - enrichment: 'CreateEnrichment', - *, - file: BinaryIO = None, + def create_expansions(self, project_id: str, collection_id: str, + expansions: List['Expansion'], **kwargs) -> DetailedResponse: """ - Create an enrichment. + Create or update an expansion list. - Create an enrichment for use with the specified project. + Creates or replaces the expansion list for this collection. An expansion list + introduces alternative wording for key terms that are mentioned in your + collection. By identifying synonyms or common misspellings, you expand the scope + of a query beyond exact matches. The maximum number of expanded terms allowed per + collection is 5,000. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param CreateEnrichment enrichment: Information about a specific - enrichment. - :param BinaryIO file: (optional) The enrichment file to upload. + :param str collection_id: The ID of the collection. + :param List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to + include all expanded terms. For example, a query for `ibm` expands to `ibm + OR international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced + by the terms in `expanded_terms`. For example, a query for the often + misused term `on premise` is converted to `on premises OR on-premises` and + does not contain the original term. If you want an input term to be + included in the query, then repeat the input term in the expanded terms + list. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment is None: - raise ValueError('enrichment must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if expansions is None: + raise ValueError('expansions must be provided') + expansions = [convert_model(x) for x in expansions] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_enrichment') + operation_id='create_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - form_data = [] - form_data.append( - ('enrichment', (None, json.dumps(enrichment), 'application/json'))) - if file: - form_data.append(('file', (None, file, 'application/octet-stream'))) + data = { + 'expansions': expansions, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, params=params, - files=form_data) + data=data) response = self.send(request, **kwargs) return response - def get_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + def delete_expansions(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Get enrichment. + Delete the expansion list. - Get details about a specific enrichment. + Removes the expansion information for this collection. To disable query expansion + for a collection, delete the expansion list. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. + :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_enrichment') + operation_id='delete_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='GET', + request = self.prepare_request(method='DELETE', url=url, headers=headers, params=params) @@ -1577,102 +1833,95 @@ def get_enrichment(self, project_id: str, enrichment_id: str, response = self.send(request, **kwargs) return response - def update_enrichment(self, - project_id: str, - enrichment_id: str, - name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + ######################### + # Component settings + ######################### + + def get_component_settings(self, project_id: str, + **kwargs) -> DetailedResponse: """ - Update an enrichment. + List component settings. - Updates an existing enrichment's name and description. + Returns default configuration settings for components. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. - :param str name: A new name for the enrichment. - :param str description: (optional) A new description for the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') - if name is None: - raise ValueError('name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_enrichment') + operation_id='get_component_settings') headers.update(sdk_headers) - params = {'version': self.version} - - data = {'name': name, 'description': description} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/component_settings'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def delete_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + ######################### + # Training data + ######################### + + def list_training_queries(self, project_id: str, + **kwargs) -> DetailedResponse: """ - Delete an enrichment. + List training queries. - Deletes an existing enrichment from the specified project. - **Note:** Only enrichments that have been manually created can be deleted. + List the training queries for the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_enrichment') + operation_id='list_training_queries') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', + request = self.prepare_request(method='GET', url=url, headers=headers, params=params) @@ -1680,35 +1929,42 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, response = self.send(request, **kwargs) return response - ######################### - # projects - ######################### - - def list_projects(self, **kwargs) -> DetailedResponse: + def delete_training_queries(self, project_id: str, + **kwargs) -> DetailedResponse: """ - List projects. + Delete training queries. - Lists existing projects for this instance. + Removes all training queries for the specified project. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListProjectsResponse` object + :rtype: DetailedResponse """ + if not project_id: + raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_projects') + operation_id='delete_training_queries') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - url = '/v2/projects' - request = self.prepare_request(method='GET', + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', url=url, headers=headers, params=params) @@ -1716,48 +1972,52 @@ def list_projects(self, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def create_project(self, - name: str, - type: str, - *, - default_query_parameters: 'DefaultQueryParams' = None, - **kwargs) -> DetailedResponse: + def create_training_query(self, + project_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: str = None, + **kwargs) -> DetailedResponse: """ - Create a Project. + Create training query. - Create a new project for this instance. + Add a query to the training data for this project. The query can contain a filter + and natural language query. - :param str name: The human readable name of this project. - :param str type: The type of project. - The `content_intelligence` type is a *Document Retrieval for Contracts* - project and the `other` type is a *Custom* project. - The `content_mining` and `content_intelligence` types are available with - Premium plan managed deployments and installed deployments only. - :param DefaultQueryParams default_query_parameters: (optional) Default - query parameters for this project. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str natural_language_query: The natural text query that is used as + the training query. + :param List[TrainingExample] examples: Array of training examples. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if name is None: - raise ValueError('name must be provided') - if type is None: - raise ValueError('type must be provided') - if default_query_parameters is not None: - default_query_parameters = convert_model(default_query_parameters) + if not project_id: + raise ValueError('project_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') + examples = [convert_model(x) for x in examples] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_project') + operation_id='create_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { - 'name': name, - 'type': type, - 'default_query_parameters': default_query_parameters + 'natural_language_query': natural_language_query, + 'examples': examples, + 'filter': filter, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1765,9 +2025,14 @@ def create_project(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - url = '/v2/projects' + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1777,37 +2042,46 @@ def create_project(self, response = self.send(request, **kwargs) return response - def get_project(self, project_id: str, **kwargs) -> DetailedResponse: + def get_training_query(self, project_id: str, query_id: str, + **kwargs) -> DetailedResponse: """ - Get project. + Get a training data query. - Get details on the specified project. + Get details for a specific training data query, including the query string and all + examples. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not query_id: + raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_project') + operation_id='get_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1816,47 +2090,70 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def update_project(self, - project_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def update_training_query(self, + project_id: str, + query_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: str = None, + **kwargs) -> DetailedResponse: """ - Update a project. + Update a training query. - Update the specified project's name. + Updates an existing training query and it's examples. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str name: (optional) The new name to give this project. + :param str query_id: The ID of the query used for training. + :param str natural_language_query: The natural text query that is used as + the training query. + :param List[TrainingExample] examples: Array of training examples. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not query_id: + raise ValueError('query_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') + examples = [convert_model(x) for x in examples] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_project') + operation_id='update_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name} + data = { + 'natural_language_query': natural_language_query, + 'examples': examples, + 'filter': filter, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1866,38 +2163,45 @@ def update_project(self, response = self.send(request, **kwargs) return response - def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: + def delete_training_query(self, project_id: str, query_id: str, + **kwargs) -> DetailedResponse: """ - Delete a project. + Delete a training data query. - Deletes the specified project. - **Important:** Deleting a project deletes everything that is part of the specified - project, including all collections. + Removes details from a training data query, including the query string and all + examples. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') + if not query_id: + raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_project') + operation_id='delete_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1907,43 +2211,46 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: return response ######################### - # userData + # Enrichments ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: """ - Delete labeled data. + List enrichments. - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - You associate a customer ID with data by passing the **X-Watson-Metadata** header - with a request that passes data. For more information about personal data and - customer IDs, see [Information - security](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-information-security#information-security). - **Note:** This method is only supported on IBM Cloud instances of Discovery. + Lists the enrichments available to this project. The *Part of Speech* and + *Sentiment of Phrases* enrichments might be listed, but are reserved for internal + use only. - :param str customer_id: The customer ID for which all data is to be - deleted. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Enrichments` object """ - if customer_id is None: - raise ValueError('customer_id must be provided') + if not project_id: + raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_user_data') + operation_id='list_enrichments') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - url = '/v2/user_data' - request = self.prepare_request(method='DELETE', + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + request = self.prepare_request(method='GET', url=url, headers=headers, params=params) @@ -1951,110 +2258,1930 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response + def create_enrichment(self, + project_id: str, + enrichment: 'CreateEnrichment', + *, + file: BinaryIO = None, + **kwargs) -> DetailedResponse: + """ + Create an enrichment. -class AddDocumentEnums: - """ - Enums for add_document parameters. - """ + Create an enrichment for use with the specified project. To apply the enrichment + to a collection in the project, use the [Collections + API](/apidocs/discovery-data#createcollection). - class FileContentType(str, Enum): - """ - The content type of file. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param CreateEnrichment enrichment: Information about a specific + enrichment. + :param BinaryIO file: (optional) The enrichment file to upload. Expected + file types per enrichment are as follows: + * CSV for `dictionary` + * PEAR for `uima_annotator` and `rule_based` (Explorer) + * ZIP for `watson_knowledge_studio_model` and `rule_based` (Studio Advanced + Rule Editor). + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + if not project_id: + raise ValueError('project_id must be provided') + if enrichment is None: + raise ValueError('enrichment must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_enrichment') + headers.update(sdk_headers) -class UpdateDocumentEnums: - """ - Enums for update_document parameters. - """ + params = { + 'version': self.version, + } - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + form_data = [] + form_data.append( + ('enrichment', (None, json.dumps(enrichment), 'application/json'))) + if file: + form_data.append(('file', (None, file, 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AnalyzeDocumentEnums: - """ - Enums for analyze_document parameters. - """ + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) - class FileContentType(str, Enum): + response = self.send(request, **kwargs) + return response + + def get_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> DetailedResponse: """ - The content type of file. + Get enrichment. + + Get details about a specific enrichment. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + if not project_id: + raise ValueError('project_id must be provided') + if not enrichment_id: + raise ValueError('enrichment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_enrichment') + headers.update(sdk_headers) -############################################################################## -# Models -############################################################################## + params = { + 'version': self.version, + } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AnalyzedDocument(): - """ - An object that contains the converted document and any identified enrichments. + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - :attr List[Notice] notices: (optional) Array of document results that match the - query. - :attr AnalyzedResult result: (optional) Result of the document analysis. - """ + response = self.send(request, **kwargs) + return response - def __init__(self, - *, - notices: List['Notice'] = None, - result: 'AnalyzedResult' = None) -> None: + def update_enrichment(self, + project_id: str, + enrichment_id: str, + name: str, + *, + description: str = None, + **kwargs) -> DetailedResponse: """ - Initialize a AnalyzedDocument object. + Update an enrichment. - :param List[Notice] notices: (optional) Array of document results that - match the query. - :param AnalyzedResult result: (optional) Result of the document analysis. + Updates an existing enrichment's name and description. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str enrichment_id: The ID of the enrichment. + :param str name: A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - self.notices = notices - self.result = result - @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': - """Initialize a AnalyzedDocument object from a json dictionary.""" - args = {} - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - if 'result' in _dict: - args['result'] = AnalyzedResult.from_dict(_dict.get('result')) + if not project_id: + raise ValueError('project_id must be provided') + if not enrichment_id: + raise ValueError('enrichment_id must be provided') + if name is None: + raise ValueError('name must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_enrichment') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def delete_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> DetailedResponse: + """ + Delete an enrichment. + + Deletes an existing enrichment from the specified project. + **Note:** Only enrichments that have been manually created can be deleted. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not enrichment_id: + raise ValueError('enrichment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_enrichment') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + ######################### + # Document classifiers + ######################### + + def list_document_classifiers(self, project_id: str, + **kwargs) -> DetailedResponse: + """ + List document classifiers. + + Get a list of the document classifiers in a project. Returns only the name and + classifier ID of each document classifier. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifiers` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifiers') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def create_document_classifier(self, + project_id: str, + training_data: BinaryIO, + classifier: 'CreateDocumentClassifier', + *, + test_data: BinaryIO = None, + **kwargs) -> DetailedResponse: + """ + Create a document classifier. + + Create a document classifier. You can use the API to create a document classifier + in any project type. After you create a document classifier, you can use the + Enrichments API to create a classifier enrichment, and then the Collections API to + apply the enrichment to a collection in the project. + **Note:** This method is supported on installed instances (IBM Cloud Pak for Data) + or IBM Cloud-managed Premium or Enterprise plan instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param BinaryIO training_data: The training data CSV file to upload. The + CSV file must have headers. The file must include a field that contains the + text you want to classify and a field that contains the classification + labels that you want to use to classify your data. If you want to specify + multiple values in a single field, use a semicolon as the value separator. + For a sample file, see [the product + documentation](/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + :param CreateDocumentClassifier classifier: An object that manages the + settings and data that is required to train a document classification + model. + :param BinaryIO test_data: (optional) The CSV with test data to upload. The + column values in the test file must be the same as the column values in the + training data file. If no test data is provided, the training data is split + into two separate groups of training and test data. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + if classifier is None: + raise ValueError('classifier must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + form_data.append(('training_data', (None, training_data, 'text/csv'))) + form_data.append( + ('classifier', (None, json.dumps(classifier), 'application/json'))) + if test_data: + form_data.append(('test_data', (None, test_data, 'text/csv'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request, **kwargs) + return response + + def get_document_classifier(self, project_id: str, classifier_id: str, + **kwargs) -> DetailedResponse: + """ + Get a document classifier. + + Get details about a specific document classifier. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def update_document_classifier(self, + project_id: str, + classifier_id: str, + classifier: 'UpdateDocumentClassifier', + *, + training_data: BinaryIO = None, + test_data: BinaryIO = None, + **kwargs) -> DetailedResponse: + """ + Update a document classifier. + + Update the document classifier name or description, update the training data, or + add or update the test data. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param UpdateDocumentClassifier classifier: An object that contains a new + name or description for a document classifier, updated training data, or + new or updated test data. + :param BinaryIO training_data: (optional) The training data CSV file to + upload. The CSV file must have headers. The file must include a field that + contains the text you want to classify and a field that contains the + classification labels that you want to use to classify your data. If you + want to specify multiple values in a single column, use a semicolon as the + value separator. For a sample file, see [the product + documentation](/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + :param BinaryIO test_data: (optional) The CSV with test data to upload. The + column values in the test file must be the same as the column values in the + training data file. If no test data is provided, the training data is split + into two separate groups of training and test data. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if classifier is None: + raise ValueError('classifier must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + form_data.append( + ('classifier', (None, json.dumps(classifier), 'application/json'))) + if training_data: + form_data.append( + ('training_data', (None, training_data, 'text/csv'))) + if test_data: + form_data.append(('test_data', (None, test_data, 'text/csv'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request, **kwargs) + return response + + def delete_document_classifier(self, project_id: str, classifier_id: str, + **kwargs) -> DetailedResponse: + """ + Delete a document classifier. + + Deletes an existing document classifier from the specified project. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + ######################### + # Document classifier models + ######################### + + def list_document_classifier_models(self, project_id: str, + classifier_id: str, + **kwargs) -> DetailedResponse: + """ + List document classifier models. + + Get a list of the document classifier models in a project. Returns only the name + and model ID of each document classifier model. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModels` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifier_models') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def create_document_classifier_model( + self, + project_id: str, + classifier_id: str, + name: str, + *, + description: str = None, + learning_rate: float = None, + l1_regularization_strengths: List[float] = None, + l2_regularization_strengths: List[float] = None, + training_max_steps: int = None, + improvement_ratio: float = None, + **kwargs) -> DetailedResponse: + """ + Create a document classifier model. + + Create a document classifier model by training a model that uses the data and + classifier settings defined in the specified document classifier. + **Note:** This method is supported on installed intances (IBM Cloud Pak for Data) + or IBM Cloud-managed Premium or Enterprise plan instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str name: The name of the document classifier model. + :param str description: (optional) A description of the document classifier + model. + :param float learning_rate: (optional) A tuning parameter in an + optimization algorithm that determines the step size at each iteration of + the training process. It influences how much of any newly acquired + information overrides the existing information, and therefore is said to + represent the speed at which a machine learning model learns. The default + value is `0.1`. + :param List[float] l1_regularization_strengths: (optional) Avoids + overfitting by shrinking the coefficient of less important features to + zero, which removes some features altogether. You can specify many values + for hyper-parameter optimization. The default value is `[0.000001]`. + :param List[float] l2_regularization_strengths: (optional) A method you can + apply to avoid overfitting your model on the training data. You can specify + many values for hyper-parameter optimization. The default value is + `[0.000001]`. + :param int training_max_steps: (optional) Maximum number of training steps + to complete. This setting is useful if you need the training process to + finish in a specific time frame to fit into an automated process. The + default value is ten million. + :param float improvement_ratio: (optional) Stops the training run early if + the improvement ratio is not met by the time the process reaches a certain + point. The default value is `0.00001`. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if name is None: + raise ValueError('name must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier_model') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + 'learning_rate': learning_rate, + 'l1_regularization_strengths': l1_regularization_strengths, + 'l2_regularization_strengths': l2_regularization_strengths, + 'training_max_steps': training_max_steps, + 'improvement_ratio': improvement_ratio, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def get_document_classifier_model(self, project_id: str, classifier_id: str, + model_id: str, + **kwargs) -> DetailedResponse: + """ + Get a document classifier model. + + Get details about a specific document classifier model. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str model_id: The ID of the classifier model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if not model_id: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier_model') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def update_document_classifier_model(self, + project_id: str, + classifier_id: str, + model_id: str, + *, + name: str = None, + description: str = None, + **kwargs) -> DetailedResponse: + """ + Update a document classifier model. + + Update the document classifier model name or description. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str model_id: The ID of the classifier model. + :param str name: (optional) A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if not model_id: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier_model') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def delete_document_classifier_model(self, project_id: str, + classifier_id: str, model_id: str, + **kwargs) -> DetailedResponse: + """ + Delete a document classifier model. + + Deletes an existing document classifier model from the specified project. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str model_id: The ID of the classifier model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not classifier_id: + raise ValueError('classifier_id must be provided') + if not model_id: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier_model') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + ######################### + # Analyze + ######################### + + def analyze_document(self, + project_id: str, + collection_id: str, + *, + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + **kwargs) -> DetailedResponse: + """ + Analyze a Document. + + Process a document and return it for realtime use. Supports JSON files only. + The file is not stored in the collection, but is processed according to the + collection's configuration settings. To get results, enrichments must be applied + to a field in the collection that also exists in the file that you want to + analyze. For example, to analyze text in a `Quote` field, you must apply + enrichments to the `Quote` field in the collection configuration. Then, when you + analyze the file, the text in the `Quote` field is analyzed and results are + written to a field named `enriched_Quote`. + **Note:** This method is supported with Enterprise plan deployments and installed + deployments only. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. + :param BinaryIO file: (optional) When adding a document, the content of the + document to ingest. For maximum supported file size limits, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + When analyzing a document, the content of the document to analyze but not + ingest. Only the `application/json` content type is supported currently. + For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='analyze_document') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) + if metadata: + form_data.append(('metadata', (None, metadata, 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request, **kwargs) + return response + + ######################### + # User data + ######################### + + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + You associate a customer ID with data by passing the **X-Watson-Metadata** header + with a request that passes data. For more information about personal data and + customer IDs, see [Information + security](/docs/discovery-data?topic=discovery-data-information-security#information-security). + **Note:** This method is only supported on IBM Cloud instances of Discovery. + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not customer_id: + raise ValueError('customer_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'customer_id': customer_id, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + url = '/v2/user_data' + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + +class AddDocumentEnums: + """ + Enums for add_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class UpdateDocumentEnums: + """ + Enums for update_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class AnalyzeDocumentEnums: + """ + Enums for analyze_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +############################################################################## +# Models +############################################################################## + + +class AnalyzedDocument(): + """ + An object that contains the converted document and any identified enrichments. + Root-level fields from the original file are returned also. + + :attr List[Notice] notices: (optional) Array of notices that are triggered when + the files are processed. + :attr AnalyzedResult result: (optional) Result of the document analysis. + """ + + def __init__(self, + *, + notices: List['Notice'] = None, + result: 'AnalyzedResult' = None) -> None: + """ + Initialize a AnalyzedDocument object. + + :param List[Notice] notices: (optional) Array of notices that are triggered + when the files are processed. + :param AnalyzedResult result: (optional) Result of the document analysis. + """ + self.notices = notices + self.result = result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': + """Initialize a AnalyzedDocument object from a json dictionary.""" + args = {} + if 'notices' in _dict: + args['notices'] = [ + Notice.from_dict(v) for v in _dict.get('notices') + ] + if 'result' in _dict: + args['result'] = AnalyzedResult.from_dict(_dict.get('result')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedDocument object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'notices') and self.notices is not None: + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list + if hasattr(self, 'result') and self.result is not None: + if isinstance(self.result, dict): + _dict['result'] = self.result + else: + _dict['result'] = self.result.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AnalyzedDocument object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedDocument') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AnalyzedDocument') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AnalyzedResult(): + """ + Result of the document analysis. + + :attr dict metadata: (optional) Metadata that was specified with the request. + """ + + # The set of defined properties for the class + _properties = frozenset(['metadata']) + + def __init__(self, *, metadata: dict = None, **kwargs) -> None: + """ + Initialize a AnalyzedResult object. + + :param dict metadata: (optional) Metadata that was specified with the + request. + :param **kwargs: (optional) Any additional properties. + """ + self.metadata = metadata + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': + """Initialize a AnalyzedResult object from a json dictionary.""" + args = {} + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in AnalyzedResult._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this AnalyzedResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AnalyzedResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ClassifierFederatedModel(): + """ + An object with details for creating federated document classifier models. + + :attr str field: Name of the field that contains the values from which multiple + classifier models are defined. For example, you can specify a field that lists + product lines to create a separate model per product line. + """ + + def __init__(self, field: str) -> None: + """ + Initialize a ClassifierFederatedModel object. + + :param str field: Name of the field that contains the values from which + multiple classifier models are defined. For example, you can specify a + field that lists product lines to create a separate model per product line. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassifierFederatedModel': + """Initialize a ClassifierFederatedModel object from a json dictionary.""" + args = {} + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in ClassifierFederatedModel JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierFederatedModel object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ClassifierFederatedModel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassifierFederatedModel') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ClassifierFederatedModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ClassifierModelEvaluation(): + """ + An object that contains information about a trained document classifier model. + + :attr ModelEvaluationMicroAverage micro_average: A micro-average aggregates the + contributions of all classes to compute the average metric. Classes refers to + the classification labels that are specified in the **answer_field**. + :attr ModelEvaluationMacroAverage macro_average: A macro-average computes metric + independently for each class and then takes the average. Class refers to the + classification label that is specified in the **answer_field**. + :attr List[PerClassModelEvaluation] per_class: An array of evaluation metrics, + one set of metrics for each class, where class refers to the classification + label that is specified in the **answer_field**. + """ + + def __init__(self, micro_average: 'ModelEvaluationMicroAverage', + macro_average: 'ModelEvaluationMacroAverage', + per_class: List['PerClassModelEvaluation']) -> None: + """ + Initialize a ClassifierModelEvaluation object. + + :param ModelEvaluationMicroAverage micro_average: A micro-average + aggregates the contributions of all classes to compute the average metric. + Classes refers to the classification labels that are specified in the + **answer_field**. + :param ModelEvaluationMacroAverage macro_average: A macro-average computes + metric independently for each class and then takes the average. Class + refers to the classification label that is specified in the + **answer_field**. + :param List[PerClassModelEvaluation] per_class: An array of evaluation + metrics, one set of metrics for each class, where class refers to the + classification label that is specified in the **answer_field**. + """ + self.micro_average = micro_average + self.macro_average = macro_average + self.per_class = per_class + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassifierModelEvaluation': + """Initialize a ClassifierModelEvaluation object from a json dictionary.""" + args = {} + if 'micro_average' in _dict: + args['micro_average'] = ModelEvaluationMicroAverage.from_dict( + _dict.get('micro_average')) + else: + raise ValueError( + 'Required property \'micro_average\' not present in ClassifierModelEvaluation JSON' + ) + if 'macro_average' in _dict: + args['macro_average'] = ModelEvaluationMacroAverage.from_dict( + _dict.get('macro_average')) + else: + raise ValueError( + 'Required property \'macro_average\' not present in ClassifierModelEvaluation JSON' + ) + if 'per_class' in _dict: + args['per_class'] = [ + PerClassModelEvaluation.from_dict(v) + for v in _dict.get('per_class') + ] + else: + raise ValueError( + 'Required property \'per_class\' not present in ClassifierModelEvaluation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierModelEvaluation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'micro_average') and self.micro_average is not None: + if isinstance(self.micro_average, dict): + _dict['micro_average'] = self.micro_average + else: + _dict['micro_average'] = self.micro_average.to_dict() + if hasattr(self, 'macro_average') and self.macro_average is not None: + if isinstance(self.macro_average, dict): + _dict['macro_average'] = self.macro_average + else: + _dict['macro_average'] = self.macro_average.to_dict() + if hasattr(self, 'per_class') and self.per_class is not None: + per_class_list = [] + for v in self.per_class: + if isinstance(v, dict): + per_class_list.append(v) + else: + per_class_list.append(v.to_dict()) + _dict['per_class'] = per_class_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ClassifierModelEvaluation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassifierModelEvaluation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ClassifierModelEvaluation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Collection(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: (optional) The name of the collection. + """ + + def __init__(self, *, collection_id: str = None, name: str = None) -> None: + """ + Initialize a Collection object. + + :param str name: (optional) The name of the collection. + """ + self.collection_id = collection_id + self.name = name + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Collection': + """Initialize a Collection object from a json dictionary.""" + args = {} + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Collection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Collection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Collection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetails(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: The name of the collection. + :attr str description: (optional) A description of the collection. + :attr datetime created: (optional) The date that the collection was created. + :attr str language: (optional) The language of the collection. For a list of + supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments + that are applied to this collection. To get a list of enrichments that are + available for a project, use the [List enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about project + default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). + :attr CollectionDetailsSmartDocumentUnderstanding smart_document_understanding: + (optional) An object that describes the Smart Document Understanding model for a + collection. + """ + + def __init__( + self, + name: str, + *, + collection_id: str = None, + description: str = None, + created: datetime = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None, + smart_document_understanding: + 'CollectionDetailsSmartDocumentUnderstanding' = None + ) -> None: + """ + Initialize a CollectionDetails object. + + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. For a list + of supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of + enrichments that are available for a project, use the [List + enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about + project default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). + """ + self.collection_id = collection_id + self.name = name + self.description = description + self.created = created + self.language = language + self.enrichments = enrichments + self.smart_document_understanding = smart_document_understanding + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionDetails': + """Initialize a CollectionDetails object from a json dictionary.""" + args = {} + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in CollectionDetails JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'enrichments' in _dict: + args['enrichments'] = [ + CollectionEnrichment.from_dict(v) + for v in _dict.get('enrichments') + ] + if 'smart_document_understanding' in _dict: + args[ + 'smart_document_understanding'] = CollectionDetailsSmartDocumentUnderstanding.from_dict( + _dict.get('smart_document_understanding')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetails object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'enrichments') and self.enrichments is not None: + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list + if hasattr(self, 'smart_document_understanding') and getattr( + self, 'smart_document_understanding') is not None: + if isinstance(getattr(self, 'smart_document_understanding'), dict): + _dict['smart_document_understanding'] = getattr( + self, 'smart_document_understanding') + else: + _dict['smart_document_understanding'] = getattr( + self, 'smart_document_understanding').to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CollectionDetails') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CollectionDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetailsSmartDocumentUnderstanding(): + """ + An object that describes the Smart Document Understanding model for a collection. + + :attr bool enabled: (optional) When `true`, smart document understanding + conversion is enabled for the collection. + :attr str model: (optional) Specifies the type of Smart Document Understanding + (SDU) model that is enabled for the collection. The following types of models + are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is applied + automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the types + of documents in the collection (as long as the service plan supports SDU + models). + You can apply user-trained or pretrained models to collections from the + *Identify fields* page of the product user interface. For more information, see + [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + + def __init__(self, *, enabled: bool = None, model: str = None) -> None: + """ + Initialize a CollectionDetailsSmartDocumentUnderstanding object. + + :param bool enabled: (optional) When `true`, smart document understanding + conversion is enabled for the collection. + :param str model: (optional) Specifies the type of Smart Document + Understanding (SDU) model that is enabled for the collection. The following + types of models are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is + applied automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the + types of documents in the collection (as long as the service plan supports + SDU models). + You can apply user-trained or pretrained models to collections from the + *Identify fields* page of the product user interface. For more information, + see [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + self.enabled = enabled + self.model = model + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'CollectionDetailsSmartDocumentUnderstanding': + """Initialize a CollectionDetailsSmartDocumentUnderstanding object from a json dictionary.""" + args = {} + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'model' in _dict: + args['model'] = _dict.get('model') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetailsSmartDocumentUnderstanding object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionDetailsSmartDocumentUnderstanding object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'CollectionDetailsSmartDocumentUnderstanding') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'CollectionDetailsSmartDocumentUnderstanding') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ModelEnum(str, Enum): + """ + Specifies the type of Smart Document Understanding (SDU) model that is enabled for + the collection. The following types of models are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is applied + automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the types + of documents in the collection (as long as the service plan supports SDU models). + You can apply user-trained or pretrained models to collections from the *Identify + fields* page of the product user interface. For more information, see [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + CUSTOM = 'custom' + PRE_TRAINED = 'pre_trained' + TEXT_EXTRACTION = 'text_extraction' + + +class CollectionEnrichment(): + """ + An object describing an enrichment for a collection. + + :attr str enrichment_id: (optional) The unique identifier of this enrichment. + For more information about how to determine the ID of an enrichment, see [the + product + documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). + :attr List[str] fields: (optional) An array of field names that the enrichment + is applied to. + If you apply an enrichment to a field from a JSON file, the data is converted to + an array automatically, even if the field contains a single value. + """ + + def __init__(self, + *, + enrichment_id: str = None, + fields: List[str] = None) -> None: + """ + Initialize a CollectionEnrichment object. + + :param str enrichment_id: (optional) The unique identifier of this + enrichment. For more information about how to determine the ID of an + enrichment, see [the product + documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). + :param List[str] fields: (optional) An array of field names that the + enrichment is applied to. + If you apply an enrichment to a field from a JSON file, the data is + converted to an array automatically, even if the field contains a single + value. + """ + self.enrichment_id = enrichment_id + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': + """Initialize a CollectionEnrichment object from a json dictionary.""" + args = {} + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionEnrichment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CollectionEnrichment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Completions(): + """ + An object that contains an array of autocompletion suggestions. + + :attr List[str] completions: (optional) Array of autocomplete suggestion based + on the provided prefix. + """ + + def __init__(self, *, completions: List[str] = None) -> None: + """ + Initialize a Completions object. + + :param List[str] completions: (optional) Array of autocomplete suggestion + based on the provided prefix. + """ + self.completions = completions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Completions': + """Initialize a Completions object from a json dictionary.""" + args = {} + if 'completions' in _dict: + args['completions'] = _dict.get('completions') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'completions') and self.completions is not None: + _dict['completions'] = self.completions + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Completions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Completions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Completions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsAggregation(): + """ + Display settings for aggregations. + + :attr str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :attr str label: (optional) User-friendly alias for the aggregation. + :attr bool multiple_selections_allowed: (optional) Whether users is allowed to + select more than one of the aggregation terms. + :attr str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + + def __init__(self, + *, + name: str = None, + label: str = None, + multiple_selections_allowed: bool = None, + visualization_type: str = None) -> None: + """ + Initialize a ComponentSettingsAggregation object. + + :param str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is + allowed to select more than one of the aggregation terms. + :param str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + self.name = name + self.label = label + self.multiple_selections_allowed = multiple_selections_allowed + self.visualization_type = visualization_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'label' in _dict: + args['label'] = _dict.get('label') + if 'multiple_selections_allowed' in _dict: + args['multiple_selections_allowed'] = _dict.get( + 'multiple_selections_allowed') + if 'visualization_type' in _dict: + args['visualization_type'] = _dict.get('visualization_type') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AnalyzedDocument object from a json dictionary.""" + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - if hasattr(self, 'result') and self.result is not None: - _dict['result'] = self.result.to_dict() + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'multiple_selections_allowed' + ) and self.multiple_selections_allowed is not None: + _dict[ + 'multiple_selections_allowed'] = self.multiple_selections_allowed + if hasattr( + self, + 'visualization_type') and self.visualization_type is not None: + _dict['visualization_type'] = self.visualization_type return _dict def _to_dict(self): @@ -2062,151 +4189,306 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AnalyzedDocument object.""" + """Return a `str` version of this ComponentSettingsAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalyzedDocument') -> bool: + def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'AnalyzedDocument') -> bool: + def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class VisualizationTypeEnum(str, Enum): + """ + Type of visualization to use when rendering the aggregation. + """ + AUTO = 'auto' + FACET_TABLE = 'facet_table' + WORD_CLOUD = 'word_cloud' + MAP = 'map' -class AnalyzedResult(): - """ - Result of the document analysis. - :attr dict metadata: (optional) Metadata of the document. +class ComponentSettingsFieldsShown(): """ + Fields shown in the results section of the UI. - # The set of defined properties for the class - _properties = frozenset(['metadata']) + :attr ComponentSettingsFieldsShownBody body: (optional) Body label. + :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ - def __init__(self, *, metadata: dict = None, **kwargs) -> None: + def __init__(self, + *, + body: 'ComponentSettingsFieldsShownBody' = None, + title: 'ComponentSettingsFieldsShownTitle' = None) -> None: """ - Initialize a AnalyzedResult object. + Initialize a ComponentSettingsFieldsShown object. - :param dict metadata: (optional) Metadata of the document. - :param **kwargs: (optional) Any additional properties. + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. """ - self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.body = body + self.title = title @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': - """Initialize a AnalyzedResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" args = {} - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if 'body' in _dict: + args['body'] = ComponentSettingsFieldsShownBody.from_dict( + _dict.get('body')) + if 'title' in _dict: + args['title'] = ComponentSettingsFieldsShownTitle.from_dict( + _dict.get('title')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AnalyzedResult object from a json dictionary.""" + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'body') and self.body is not None: + if isinstance(self.body, dict): + _dict['body'] = self.body + else: + _dict['body'] = self.body.to_dict() + if hasattr(self, 'title') and self.title is not None: + if isinstance(self.title, dict): + _dict['title'] = self.title + else: + _dict['title'] = self.title.to_dict() return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" - _dict = {} + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsFieldsShown object.""" + return json.dumps(self.to_dict(), indent=2) - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - _dict[_key] = getattr(self, _key) + def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownBody(): + """ + Body label. + + :attr bool use_passage: (optional) Use the whole passage as the body. + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + """ + Initialize a ComponentSettingsFieldsShownBody object. + + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. + """ + self.use_passage = use_passage + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + args = {} + if 'use_passage' in _dict: + args['use_passage'] = _dict.get('use_passage') + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'use_passage') and self.use_passage is not None: + _dict['use_passage'] = self.use_passage + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field return _dict - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - delattr(self, _key) + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() - for _key, _value in _dict.items(): - if _key not in AnalyzedResult._properties: - setattr(self, _key, _value) + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownTitle(): + """ + Title label. + + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, field: str = None) -> None: + """ + Initialize a ComponentSettingsFieldsShownTitle object. + + :param str field: (optional) Use a specific field as the title. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + args = {} + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AnalyzedResult object.""" + """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalyzedResult') -> bool: + def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'AnalyzedResult') -> bool: + def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Collection(): +class ComponentSettingsResponse(): """ - A collection for storing documents. + The default component settings for this project. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. + :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + results section of the UI. + :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. + :attr bool structured_search: (optional) Whether or not structured search is + enabled. + :attr int results_per_page: (optional) Number or results shown per page. + :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of + component setting aggregations. """ - def __init__(self, *, collection_id: str = None, name: str = None) -> None: + def __init__( + self, + *, + fields_shown: 'ComponentSettingsFieldsShown' = None, + autocomplete: bool = None, + structured_search: bool = None, + results_per_page: int = None, + aggregations: List['ComponentSettingsAggregation'] = None) -> None: """ - Initialize a Collection object. + Initialize a ComponentSettingsResponse object. - :param str name: (optional) The name of the collection. + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown + in the results section of the UI. + :param bool autocomplete: (optional) Whether or not autocomplete is + enabled. + :param bool structured_search: (optional) Whether or not structured search + is enabled. + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list + of component setting aggregations. """ - self.collection_id = collection_id - self.name = name + self.fields_shown = fields_shown + self.autocomplete = autocomplete + self.structured_search = structured_search + self.results_per_page = results_per_page + self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': + """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if 'fields_shown' in _dict: + args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( + _dict.get('fields_shown')) + if 'autocomplete' in _dict: + args['autocomplete'] = _dict.get('autocomplete') + if 'structured_search' in _dict: + args['structured_search'] = _dict.get('structured_search') + if 'results_per_page' in _dict: + args['results_per_page'] = _dict.get('results_per_page') + if 'aggregations' in _dict: + args['aggregations'] = [ + ComponentSettingsAggregation.from_dict(v) + for v in _dict.get('aggregations') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Collection object from a json dictionary.""" + """Initialize a ComponentSettingsResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name + if hasattr(self, 'fields_shown') and self.fields_shown is not None: + if isinstance(self.fields_shown, dict): + _dict['fields_shown'] = self.fields_shown + else: + _dict['fields_shown'] = self.fields_shown.to_dict() + if hasattr(self, 'autocomplete') and self.autocomplete is not None: + _dict['autocomplete'] = self.autocomplete + if hasattr(self, + 'structured_search') and self.structured_search is not None: + _dict['structured_search'] = self.structured_search + if hasattr(self, + 'results_per_page') and self.results_per_page is not None: + _dict['results_per_page'] = self.results_per_page + if hasattr(self, 'aggregations') and self.aggregations is not None: + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -2214,103 +4496,145 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Collection object.""" + """Return a `str` version of this ComponentSettingsResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Collection') -> bool: + def __eq__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Collection') -> bool: + def __ne__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CollectionDetails(): +class CreateDocumentClassifier(): """ - A collection for storing documents. + An object that manages the settings and data that is required to train a document + classification model. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: The name of the collection. - :attr str description: (optional) A description of the collection. - :attr datetime created: (optional) The date that the collection was created. - :attr str language: (optional) The language of the collection. - :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments - that are applied to this collection. + :attr str name: A human-readable name of the document classifier. + :attr str description: (optional) A description of the document classifier. + :attr str language: The language of the training data that is associated with + the document classifier. Language is specified by using the ISO 639-1 language + code, such as `en` for English or `ja` for Japanese. + :attr str answer_field: The name of the field from the training and test data + that contains the classification labels. + :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + enrichments to apply to the data that is used to train and test the document + classifier. The output from the enrichments is used as features by the + classifier to classify the document content both during training and at run + time. + :attr ClassifierFederatedModel federated_classification: (optional) An object + with details for creating federated document classifier models. """ - def __init__(self, - name: str, - *, - collection_id: str = None, - description: str = None, - created: datetime = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None) -> None: + def __init__( + self, + name: str, + language: str, + answer_field: str, + *, + description: str = None, + enrichments: List['DocumentClassifierEnrichment'] = None, + federated_classification: 'ClassifierFederatedModel' = None + ) -> None: """ - Initialize a CollectionDetails object. - - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str language: (optional) The language of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + Initialize a CreateDocumentClassifier object. + + :param str name: A human-readable name of the document classifier. + :param str language: The language of the training data that is associated + with the document classifier. Language is specified by using the ISO 639-1 + language code, such as `en` for English or `ja` for Japanese. + :param str answer_field: The name of the field from the training and test + data that contains the classification labels. + :param str description: (optional) A description of the document + classifier. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array + of enrichments to apply to the data that is used to train and test the + document classifier. The output from the enrichments is used as features by + the classifier to classify the document content both during training and at + run time. + :param ClassifierFederatedModel federated_classification: (optional) An + object with details for creating federated document classifier models. """ - self.collection_id = collection_id self.name = name self.description = description - self.created = created self.language = language + self.answer_field = answer_field self.enrichments = enrichments + self.federated_classification = federated_classification @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionDetails': - """Initialize a CollectionDetails object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateDocumentClassifier': + """Initialize a CreateDocumentClassifier object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( - 'Required property \'name\' not present in CollectionDetails JSON' + 'Required property \'name\' not present in CreateDocumentClassifier JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) if 'language' in _dict: args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in CreateDocumentClassifier JSON' + ) + if 'answer_field' in _dict: + args['answer_field'] = _dict.get('answer_field') + else: + raise ValueError( + 'Required property \'answer_field\' not present in CreateDocumentClassifier JSON' + ) if 'enrichments' in _dict: args['enrichments'] = [ - CollectionEnrichment.from_dict(x) - for x in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) + for v in _dict.get('enrichments') ] + if 'federated_classification' in _dict: + args[ + 'federated_classification'] = ClassifierFederatedModel.from_dict( + _dict.get('federated_classification')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CollectionDetails object from a json dictionary.""" + """Initialize a CreateDocumentClassifier object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language + if hasattr(self, 'answer_field') and self.answer_field is not None: + _dict['answer_field'] = self.answer_field if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list + if hasattr(self, 'federated_classification' + ) and self.federated_classification is not None: + if isinstance(self.federated_classification, dict): + _dict[ + 'federated_classification'] = self.federated_classification + else: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -2318,71 +4642,123 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CollectionDetails object.""" + """Return a `str` version of this CreateDocumentClassifier object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CollectionDetails') -> bool: + def __eq__(self, other: 'CreateDocumentClassifier') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'CollectionDetails') -> bool: + def __ne__(self, other: 'CreateDocumentClassifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CollectionEnrichment(): +class CreateEnrichment(): """ - An object describing an Enrichment for a collection. + Information about a specific enrichment. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. - :attr List[str] fields: (optional) An array of field names that the enrichment - is applied to. - If you apply an enrichment to a field from a JSON file, the data is converted to - an array automatically, even if the field contains a single value. + :attr str name: (optional) The human readable name for this enrichment. + :attr str description: (optional) The description of this enrichment. + :attr str type: (optional) The type of this enrichment. The following types are + supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a CSV + file. + * `regular_expression`: Creates a custom regular expression enrichment from + regex syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is + created and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis model + that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM Cloud + Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge + Studio machine learning model that is defined in a ZIP file. + :attr EnrichmentOptions options: (optional) An object that contains options for + the current enrichment. Starting with version `2020-08-30`, the enrichment + options are not included in responses from the List Enrichments method. """ def __init__(self, *, - enrichment_id: str = None, - fields: List[str] = None) -> None: + name: str = None, + description: str = None, + type: str = None, + options: 'EnrichmentOptions' = None) -> None: """ - Initialize a CollectionEnrichment object. + Initialize a CreateEnrichment object. - :param str enrichment_id: (optional) The unique identifier of this - enrichment. - :param List[str] fields: (optional) An array of field names that the - enrichment is applied to. - If you apply an enrichment to a field from a JSON file, the data is - converted to an array automatically, even if the field contains a single - value. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. The following + types are supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a + CSV file. + * `regular_expression`: Creates a custom regular expression enrichment from + regex syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is + created and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis + model that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM + Cloud Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson + Knowledge Studio machine learning model that is defined in a ZIP file. + :param EnrichmentOptions options: (optional) An object that contains + options for the current enrichment. Starting with version `2020-08-30`, the + enrichment options are not included in responses from the List Enrichments + method. """ - self.enrichment_id = enrichment_id - self.fields = fields + self.name = name + self.description = description + self.type = type + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': - """Initialize a CollectionEnrichment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': + """Initialize a CreateEnrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'options' in _dict: + args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CollectionEnrichment object from a json dictionary.""" + """Initialize a CreateEnrichment object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: - _dict['enrichment_id'] = self.enrichment_id - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = self.fields + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -2390,55 +4766,197 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CollectionEnrichment object.""" + """Return a `str` version of this CreateEnrichment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CollectionEnrichment') -> bool: + def __eq__(self, other: 'CreateEnrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'CollectionEnrichment') -> bool: + def __ne__(self, other: 'CreateEnrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of this enrichment. The following types are supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a CSV + file. + * `regular_expression`: Creates a custom regular expression enrichment from regex + syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is created + and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis model + that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM Cloud + Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge + Studio machine learning model that is defined in a ZIP file. + """ + CLASSIFIER = 'classifier' + DICTIONARY = 'dictionary' + REGULAR_EXPRESSION = 'regular_expression' + UIMA_ANNOTATOR = 'uima_annotator' + RULE_BASED = 'rule_based' + WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + -class Completions(): +class DefaultQueryParams(): """ - An object that contains an array of autocompletion suggestions. + Default query parameters for this project. - :attr List[str] completions: (optional) Array of autocomplete suggestion based - on the provided prefix. + :attr List[str] collection_ids: (optional) An array of collection identifiers to + query. If empty or omitted all collections in the project are queried. + :attr DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :attr DefaultQueryParamsTableResults table_results: (optional) Default project + query settings for table results. + :attr str aggregation: (optional) A string representing the default aggregation + query for the project. + :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) + Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic facets + from the data is deprecated. + :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions + for the query are returned by default. + :attr bool highlight: (optional) When `true`, highlights for the query are + returned by default. + :attr int count: (optional) The number of document results returned by default. + :attr str sort: (optional) A comma separated list of document fields to sort + results by default. + :attr List[str] return_: (optional) An array of field names to return in + document results if present by default. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__(self, + *, + collection_ids: List[str] = None, + passages: 'DefaultQueryParamsPassages' = None, + table_results: 'DefaultQueryParamsTableResults' = None, + aggregation: str = None, + suggested_refinements: + 'DefaultQueryParamsSuggestedRefinements' = None, + spelling_suggestions: bool = None, + highlight: bool = None, + count: int = None, + sort: str = None, + return_: List[str] = None) -> None: """ - Initialize a Completions object. + Initialize a DefaultQueryParams object. - :param List[str] completions: (optional) Array of autocomplete suggestion - based on the provided prefix. + :param List[str] collection_ids: (optional) An array of collection + identifiers to query. If empty or omitted all collections in the project + are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :param DefaultQueryParamsTableResults table_results: (optional) Default + project query settings for table results. + :param str aggregation: (optional) A string representing the default + aggregation query for the project. + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: + (optional) Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic + facets from the data is deprecated. + :param bool spelling_suggestions: (optional) When `true`, a spelling + suggestions for the query are returned by default. + :param bool highlight: (optional) When `true`, highlights for the query are + returned by default. + :param int count: (optional) The number of document results returned by + default. + :param str sort: (optional) A comma separated list of document fields to + sort results by default. + :param List[str] return_: (optional) An array of field names to return in + document results if present by default. """ - self.completions = completions + self.collection_ids = collection_ids + self.passages = passages + self.table_results = table_results + self.aggregation = aggregation + self.suggested_refinements = suggested_refinements + self.spelling_suggestions = spelling_suggestions + self.highlight = highlight + self.count = count + self.sort = sort + self.return_ = return_ @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': + """Initialize a DefaultQueryParams object from a json dictionary.""" args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if 'collection_ids' in _dict: + args['collection_ids'] = _dict.get('collection_ids') + if 'passages' in _dict: + args['passages'] = DefaultQueryParamsPassages.from_dict( + _dict.get('passages')) + if 'table_results' in _dict: + args['table_results'] = DefaultQueryParamsTableResults.from_dict( + _dict.get('table_results')) + if 'aggregation' in _dict: + args['aggregation'] = _dict.get('aggregation') + if 'suggested_refinements' in _dict: + args[ + 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( + _dict.get('suggested_refinements')) + if 'spelling_suggestions' in _dict: + args['spelling_suggestions'] = _dict.get('spelling_suggestions') + if 'highlight' in _dict: + args['highlight'] = _dict.get('highlight') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'sort' in _dict: + args['sort'] = _dict.get('sort') + if 'return' in _dict: + args['return_'] = _dict.get('return') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Completions object from a json dictionary.""" + """Initialize a DefaultQueryParams object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'completions') and self.completions is not None: - _dict['completions'] = self.completions + if hasattr(self, 'collection_ids') and self.collection_ids is not None: + _dict['collection_ids'] = self.collection_ids + if hasattr(self, 'passages') and self.passages is not None: + if isinstance(self.passages, dict): + _dict['passages'] = self.passages + else: + _dict['passages'] = self.passages.to_dict() + if hasattr(self, 'table_results') and self.table_results is not None: + if isinstance(self.table_results, dict): + _dict['table_results'] = self.table_results + else: + _dict['table_results'] = self.table_results.to_dict() + if hasattr(self, 'aggregation') and self.aggregation is not None: + _dict['aggregation'] = self.aggregation + if hasattr(self, 'suggested_refinements' + ) and self.suggested_refinements is not None: + if isinstance(self.suggested_refinements, dict): + _dict['suggested_refinements'] = self.suggested_refinements + else: + _dict[ + 'suggested_refinements'] = self.suggested_refinements.to_dict( + ) + if hasattr(self, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'sort') and self.sort is not None: + _dict['sort'] = self.sort + if hasattr(self, 'return_') and self.return_ is not None: + _dict['return'] = self.return_ return _dict def _to_dict(self): @@ -2446,90 +4964,109 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Completions object.""" + """Return a `str` version of this DefaultQueryParams object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Completions') -> bool: + def __eq__(self, other: 'DefaultQueryParams') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Completions') -> bool: + def __ne__(self, other: 'DefaultQueryParams') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsAggregation(): +class DefaultQueryParamsPassages(): """ - Display settings for aggregations. + Default settings configuration for passage search options. - :attr str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :attr str label: (optional) User-friendly alias for the aggregation. - :attr bool multiple_selections_allowed: (optional) Whether users is allowed to - select more than one of the aggregation terms. - :attr str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :attr bool enabled: (optional) When `true`, a passage search is performed by + default. + :attr int count: (optional) The number of passages to return. + :attr List[str] fields: (optional) An array of field names to perform the + passage search on. + :attr int characters: (optional) The approximate number of characters that each + returned passage will contain. + :attr bool per_document: (optional) When `true` the number of passages that can + be returned from a single document is restricted to the *max_per_document* + value. + :attr int max_per_document: (optional) The default maximum number of passages + that can be taken from a single document as the result of a passage query. """ def __init__(self, *, - name: str = None, - label: str = None, - multiple_selections_allowed: bool = None, - visualization_type: str = None) -> None: + enabled: bool = None, + count: int = None, + fields: List[str] = None, + characters: int = None, + per_document: bool = None, + max_per_document: int = None) -> None: """ - Initialize a ComponentSettingsAggregation object. + Initialize a DefaultQueryParamsPassages object. - :param str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :param str label: (optional) User-friendly alias for the aggregation. - :param bool multiple_selections_allowed: (optional) Whether users is - allowed to select more than one of the aggregation terms. - :param str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :param bool enabled: (optional) When `true`, a passage search is performed + by default. + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perform the + passage search on. + :param int characters: (optional) The approximate number of characters that + each returned passage will contain. + :param bool per_document: (optional) When `true` the number of passages + that can be returned from a single document is restricted to the + *max_per_document* value. + :param int max_per_document: (optional) The default maximum number of + passages that can be taken from a single document as the result of a + passage query. """ - self.name = name - self.label = label - self.multiple_selections_allowed = multiple_selections_allowed - self.visualization_type = visualization_type + self.enabled = enabled + self.count = count + self.fields = fields + self.characters = characters + self.per_document = per_document + self.max_per_document = max_per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'multiple_selections_allowed' in _dict: - args['multiple_selections_allowed'] = _dict.get( - 'multiple_selections_allowed') - if 'visualization_type' in _dict: - args['visualization_type'] = _dict.get('visualization_type') + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + if 'characters' in _dict: + args['characters'] = _dict.get('characters') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') + if 'max_per_document' in _dict: + args['max_per_document'] = _dict.get('max_per_document') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'multiple_selections_allowed' - ) and self.multiple_selections_allowed is not None: - _dict[ - 'multiple_selections_allowed'] = self.multiple_selections_allowed - if hasattr( - self, - 'visualization_type') and self.visualization_type is not None: - _dict['visualization_type'] = self.visualization_type + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + if hasattr(self, 'characters') and self.characters is not None: + _dict['characters'] = self.characters + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document + if hasattr(self, + 'max_per_document') and self.max_per_document is not None: + _dict['max_per_document'] = self.max_per_document return _dict def _to_dict(self): @@ -2537,74 +5074,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsAggregation object.""" + """Return a `str` version of this DefaultQueryParamsPassages object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: + def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: + def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class VisualizationTypeEnum(str, Enum): - """ - Type of visualization to use when rendering the aggregation. - """ - AUTO = 'auto' - FACET_TABLE = 'facet_table' - WORD_CLOUD = 'word_cloud' - MAP = 'map' - -class ComponentSettingsFieldsShown(): +class DefaultQueryParamsSuggestedRefinements(): """ - Fields shown in the results section of the UI. + Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic facets from + the data is deprecated. - :attr ComponentSettingsFieldsShownBody body: (optional) Body label. - :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + :attr bool enabled: (optional) When `true`, suggested refinements for the query + are returned by default. + :attr int count: (optional) The number of suggested refinements to return by + default. """ - def __init__(self, - *, - body: 'ComponentSettingsFieldsShownBody' = None, - title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + def __init__(self, *, enabled: bool = None, count: int = None) -> None: """ - Initialize a ComponentSettingsFieldsShown object. + Initialize a DefaultQueryParamsSuggestedRefinements object. - :param ComponentSettingsFieldsShownBody body: (optional) Body label. - :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param bool enabled: (optional) When `true`, suggested refinements for the + query are returned by default. + :param int count: (optional) The number of suggested refinements to return + by default. """ - self.body = body - self.title = title + self.enabled = enabled + self.count = count @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody.from_dict( - _dict.get('body')) - if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle.from_dict( - _dict.get('title')) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body.to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count return _dict def _to_dict(self): @@ -2612,60 +5141,76 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShown object.""" + """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownBody(): +class DefaultQueryParamsTableResults(): """ - Body label. + Default project query settings for table results. - :attr bool use_passage: (optional) Use the whole passage as the body. - :attr str field: (optional) Use a specific field as the title. + :attr bool enabled: (optional) When `true`, a table results for the query are + returned by default. + :attr int count: (optional) The number of table results to return by default. + :attr int per_document: (optional) The number of table results to include in + each result document. """ - def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + def __init__(self, + *, + enabled: bool = None, + count: int = None, + per_document: int = None) -> None: """ - Initialize a ComponentSettingsFieldsShownBody object. + Initialize a DefaultQueryParamsTableResults object. - :param bool use_passage: (optional) Use the whole passage as the body. - :param str field: (optional) Use a specific field as the title. + :param bool enabled: (optional) When `true`, a table results for the query + are returned by default. + :param int count: (optional) The number of table results to return by + default. + :param int per_document: (optional) The number of table results to include + in each result document. """ - self.use_passage = use_passage - self.field = field + self.enabled = enabled + self.count = count + self.per_document = per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - if 'use_passage' in _dict: - args['use_passage'] = _dict.get('use_passage') - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'use_passage') and self.use_passage is not None: - _dict['use_passage'] = self.use_passage - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document return _dict def _to_dict(self): @@ -2673,53 +5218,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + """Return a `str` version of this DefaultQueryParamsTableResults object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __eq__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownTitle(): +class DeleteDocumentResponse(): """ - Title label. + Information returned when a document is deleted. - :attr str field: (optional) Use a specific field as the title. + :attr str document_id: (optional) The unique identifier of the document. + :attr str status: (optional) Status of the document. A deleted document has the + status deleted. """ - def __init__(self, *, field: str = None) -> None: + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ - Initialize a ComponentSettingsFieldsShownTitle object. + Initialize a DeleteDocumentResponse object. - :param str field: (optional) Use a specific field as the title. + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document + has the status deleted. """ - self.field = field + self.document_id = document_id + self.status = status @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': + """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + """Initialize a DeleteDocumentResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status return _dict def _to_dict(self): @@ -2727,101 +5281,74 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" + """Return a `str` version of this DeleteDocumentResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __eq__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + Status of the document. A deleted document has the status deleted. + """ + DELETED = 'deleted' + -class ComponentSettingsResponse(): +class DocumentAccepted(): """ - The default component settings for this project. + Information returned after an uploaded document is accepted. - :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the - results section of the UI. - :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. - :attr bool structured_search: (optional) Whether or not structured search is - enabled. - :attr int results_per_page: (optional) Number or results shown per page. - :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of - component setting aggregations. + :attr str document_id: (optional) The unique identifier of the ingested + document. + :attr str status: (optional) Status of the document in the ingestion process. A + status of `processing` is returned for documents that are ingested with a + *version* date before `2019-01-01`. The `pending` status is returned for all + others. """ - def __init__( - self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None) -> None: + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ - Initialize a ComponentSettingsResponse object. + Initialize a DocumentAccepted object. - :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown - in the results section of the UI. - :param bool autocomplete: (optional) Whether or not autocomplete is - enabled. - :param bool structured_search: (optional) Whether or not structured search - is enabled. - :param int results_per_page: (optional) Number or results shown per page. - :param List[ComponentSettingsAggregation] aggregations: (optional) a list - of component setting aggregations. + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion + process. A status of `processing` is returned for documents that are + ingested with a *version* date before `2019-01-01`. The `pending` status is + returned for all others. """ - self.fields_shown = fields_shown - self.autocomplete = autocomplete - self.structured_search = structured_search - self.results_per_page = results_per_page - self.aggregations = aggregations + self.document_id = document_id + self.status = status @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': + """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - if 'fields_shown' in _dict: - args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( - _dict.get('fields_shown')) - if 'autocomplete' in _dict: - args['autocomplete'] = _dict.get('autocomplete') - if 'structured_search' in _dict: - args['structured_search'] = _dict.get('structured_search') - if 'results_per_page' in _dict: - args['results_per_page'] = _dict.get('results_per_page') - if 'aggregations' in _dict: - args['aggregations'] = [ - ComponentSettingsAggregation.from_dict(x) - for x in _dict.get('aggregations') - ] + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + """Initialize a DocumentAccepted object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'fields_shown') and self.fields_shown is not None: - _dict['fields_shown'] = self.fields_shown.to_dict() - if hasattr(self, 'autocomplete') and self.autocomplete is not None: - _dict['autocomplete'] = self.autocomplete - if hasattr(self, - 'structured_search') and self.structured_search is not None: - _dict['structured_search'] = self.structured_search - if hasattr(self, - 'results_per_page') and self.results_per_page is not None: - _dict['results_per_page'] = self.results_per_page - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status return _dict def _to_dict(self): @@ -2829,84 +5356,88 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsResponse object.""" + """Return a `str` version of this DocumentAccepted object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsResponse') -> bool: + def __eq__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ComponentSettingsResponse') -> bool: + def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + Status of the document in the ingestion process. A status of `processing` is + returned for documents that are ingested with a *version* date before + `2019-01-01`. The `pending` status is returned for all others. + """ + PROCESSING = 'processing' + PENDING = 'pending' + -class CreateEnrichment(): +class DocumentAttribute(): """ - Information about a specific enrichment. + List of document attributes. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) An object that contains options for - the current enrichment. Starting with version `2020-08-30`, the enrichment - options are not included in responses from the List Enrichments method. + :attr str type: (optional) The type of attribute. + :attr str text: (optional) The text associated with the attribute. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. """ def __init__(self, *, - name: str = None, - description: str = None, type: str = None, - options: 'EnrichmentOptions' = None) -> None: + text: str = None, + location: 'TableElementLocation' = None) -> None: """ - Initialize a CreateEnrichment object. + Initialize a DocumentAttribute object. - :param str name: (optional) The human readable name for this enrichment. - :param str description: (optional) The description of this enrichment. - :param str type: (optional) The type of this enrichment. - :param EnrichmentOptions options: (optional) An object that contains - options for the current enrichment. Starting with version `2020-08-30`, the - enrichment options are not included in responses from the List Enrichments - method. + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. """ - self.name = name - self.description = description self.type = type - self.options = options + self.text = text + self.location = location @classmethod - def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': - """Initialize a CreateEnrichment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': + """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') if 'type' in _dict: args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'location' in _dict: + args['location'] = TableElementLocation.from_dict( + _dict.get('location')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CreateEnrichment object from a json dictionary.""" + """Initialize a DocumentAttribute object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'location') and self.location is not None: + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2914,167 +5445,192 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CreateEnrichment object.""" + """Return a `str` version of this DocumentAttribute object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CreateEnrichment') -> bool: + def __eq__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'CreateEnrichment') -> bool: + def __ne__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of this enrichment. - """ - DICTIONARY = 'dictionary' - REGULAR_EXPRESSION = 'regular_expression' - UIMA_ANNOTATOR = 'uima_annotator' - RULE_BASED = 'rule_based' - WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' - - -class DefaultQueryParams(): - """ - Default query parameters for this project. - :attr List[str] collection_ids: (optional) An array of collection identifiers to - query. If empty or omitted all collections in the project are queried. - :attr DefaultQueryParamsPassages passages: (optional) Default settings - configuration for passage search options. - :attr DefaultQueryParamsTableResults table_results: (optional) Default project - query settings for table results. - :attr str aggregation: (optional) A string representing the default aggregation - query for the project. - :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) - Object that contains suggested refinement settings. Available with Premium plans - only. - :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions - for the query are returned by default. - :attr bool highlight: (optional) When `true`, a highlights for the query are - returned by default. - :attr int count: (optional) The number of document results returned by default. - :attr str sort: (optional) A comma separated list of document fields to sort - results by default. - :attr List[str] return_: (optional) An array of field names to return in - document results if present by default. +class DocumentClassifier(): + """ + Information about a document classifier. + + :attr str classifier_id: (optional) A unique identifier of the document + classifier. + :attr str name: A human-readable name of the document classifier. + :attr str description: (optional) A description of the document classifier. + :attr datetime created: (optional) The date that the document classifier was + created. + :attr str language: (optional) The language of the training data that is + associated with the document classifier. Language is specified by using the ISO + 639-1 language code, such as `en` for English or `ja` for Japanese. + :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + enrichments to apply to the data that is used to train and test the document + classifier. The output from the enrichments is used as features by the + classifier to classify the document content both during training and at run + time. + :attr List[str] recognized_fields: (optional) An array of fields that are used + to train the document classifier. The same set of fields must exist in the + training data, the test data, and the documents where the resulting document + classifier enrichment is applied at run time. + :attr str answer_field: (optional) The name of the field from the training and + test data that contains the classification labels. + :attr str training_data_file: (optional) Name of the CSV file with training data + that is used to train the document classifier. + :attr str test_data_file: (optional) Name of the CSV file with data that is used + to test the document classifier. If no test data is provided, a subset of the + training data is used for testing purposes. + :attr ClassifierFederatedModel federated_classification: (optional) An object + with details for creating federated document classifier models. """ - def __init__(self, - *, - collection_ids: List[str] = None, - passages: 'DefaultQueryParamsPassages' = None, - table_results: 'DefaultQueryParamsTableResults' = None, - aggregation: str = None, - suggested_refinements: - 'DefaultQueryParamsSuggestedRefinements' = None, - spelling_suggestions: bool = None, - highlight: bool = None, - count: int = None, - sort: str = None, - return_: List[str] = None) -> None: - """ - Initialize a DefaultQueryParams object. - - :param List[str] collection_ids: (optional) An array of collection - identifiers to query. If empty or omitted all collections in the project - are queried. - :param DefaultQueryParamsPassages passages: (optional) Default settings - configuration for passage search options. - :param DefaultQueryParamsTableResults table_results: (optional) Default - project query settings for table results. - :param str aggregation: (optional) A string representing the default - aggregation query for the project. - :param DefaultQueryParamsSuggestedRefinements suggested_refinements: - (optional) Object that contains suggested refinement settings. Available - with Premium plans only. - :param bool spelling_suggestions: (optional) When `true`, a spelling - suggestions for the query are returned by default. - :param bool highlight: (optional) When `true`, a highlights for the query - are returned by default. - :param int count: (optional) The number of document results returned by - default. - :param str sort: (optional) A comma separated list of document fields to - sort results by default. - :param List[str] return_: (optional) An array of field names to return in - document results if present by default. + def __init__( + self, + name: str, + *, + classifier_id: str = None, + description: str = None, + created: datetime = None, + language: str = None, + enrichments: List['DocumentClassifierEnrichment'] = None, + recognized_fields: List[str] = None, + answer_field: str = None, + training_data_file: str = None, + test_data_file: str = None, + federated_classification: 'ClassifierFederatedModel' = None + ) -> None: """ - self.collection_ids = collection_ids - self.passages = passages - self.table_results = table_results - self.aggregation = aggregation - self.suggested_refinements = suggested_refinements - self.spelling_suggestions = spelling_suggestions - self.highlight = highlight - self.count = count - self.sort = sort - self.return_ = return_ + Initialize a DocumentClassifier object. + + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document + classifier. + :param str language: (optional) The language of the training data that is + associated with the document classifier. Language is specified by using the + ISO 639-1 language code, such as `en` for English or `ja` for Japanese. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array + of enrichments to apply to the data that is used to train and test the + document classifier. The output from the enrichments is used as features by + the classifier to classify the document content both during training and at + run time. + :param List[str] recognized_fields: (optional) An array of fields that are + used to train the document classifier. The same set of fields must exist in + the training data, the test data, and the documents where the resulting + document classifier enrichment is applied at run time. + :param str answer_field: (optional) The name of the field from the training + and test data that contains the classification labels. + :param str training_data_file: (optional) Name of the CSV file with + training data that is used to train the document classifier. + :param str test_data_file: (optional) Name of the CSV file with data that + is used to test the document classifier. If no test data is provided, a + subset of the training data is used for testing purposes. + :param ClassifierFederatedModel federated_classification: (optional) An + object with details for creating federated document classifier models. + """ + self.classifier_id = classifier_id + self.name = name + self.description = description + self.created = created + self.language = language + self.enrichments = enrichments + self.recognized_fields = recognized_fields + self.answer_field = answer_field + self.training_data_file = training_data_file + self.test_data_file = test_data_file + self.federated_classification = federated_classification @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': - """Initialize a DefaultQueryParams object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifier': + """Initialize a DocumentClassifier object from a json dictionary.""" args = {} - if 'collection_ids' in _dict: - args['collection_ids'] = _dict.get('collection_ids') - if 'passages' in _dict: - args['passages'] = DefaultQueryParamsPassages.from_dict( - _dict.get('passages')) - if 'table_results' in _dict: - args['table_results'] = DefaultQueryParamsTableResults.from_dict( - _dict.get('table_results')) - if 'aggregation' in _dict: - args['aggregation'] = _dict.get('aggregation') - if 'suggested_refinements' in _dict: + if 'classifier_id' in _dict: + args['classifier_id'] = _dict.get('classifier_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in DocumentClassifier JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'enrichments' in _dict: + args['enrichments'] = [ + DocumentClassifierEnrichment.from_dict(v) + for v in _dict.get('enrichments') + ] + if 'recognized_fields' in _dict: + args['recognized_fields'] = _dict.get('recognized_fields') + if 'answer_field' in _dict: + args['answer_field'] = _dict.get('answer_field') + if 'training_data_file' in _dict: + args['training_data_file'] = _dict.get('training_data_file') + if 'test_data_file' in _dict: + args['test_data_file'] = _dict.get('test_data_file') + if 'federated_classification' in _dict: args[ - 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( - _dict.get('suggested_refinements')) - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'highlight' in _dict: - args['highlight'] = _dict.get('highlight') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'sort' in _dict: - args['sort'] = _dict.get('sort') - if 'return' in _dict: - args['return_'] = _dict.get('return') + 'federated_classification'] = ClassifierFederatedModel.from_dict( + _dict.get('federated_classification')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParams object from a json dictionary.""" + """Initialize a DocumentClassifier object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_ids') and self.collection_ids is not None: - _dict['collection_ids'] = self.collection_ids - if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = self.passages.to_dict() - if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = self.table_results.to_dict() - if hasattr(self, 'aggregation') and self.aggregation is not None: - _dict['aggregation'] = self.aggregation - if hasattr(self, 'suggested_refinements' - ) and self.suggested_refinements is not None: - _dict['suggested_refinements'] = self.suggested_refinements.to_dict( - ) - if hasattr(self, 'spelling_suggestions' - ) and self.spelling_suggestions is not None: - _dict['spelling_suggestions'] = self.spelling_suggestions - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'sort') and self.sort is not None: - _dict['sort'] = self.sort - if hasattr(self, 'return_') and self.return_ is not None: - _dict['return'] = self.return_ + if hasattr(self, 'classifier_id') and getattr( + self, 'classifier_id') is not None: + _dict['classifier_id'] = getattr(self, 'classifier_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'enrichments') and self.enrichments is not None: + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list + if hasattr(self, + 'recognized_fields') and self.recognized_fields is not None: + _dict['recognized_fields'] = self.recognized_fields + if hasattr(self, 'answer_field') and self.answer_field is not None: + _dict['answer_field'] = self.answer_field + if hasattr( + self, + 'training_data_file') and self.training_data_file is not None: + _dict['training_data_file'] = self.training_data_file + if hasattr(self, 'test_data_file') and self.test_data_file is not None: + _dict['test_data_file'] = self.test_data_file + if hasattr(self, 'federated_classification' + ) and self.federated_classification is not None: + if isinstance(self.federated_classification, dict): + _dict[ + 'federated_classification'] = self.federated_classification + else: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -3082,109 +5638,70 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParams object.""" + """Return a `str` version of this DocumentClassifier object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParams') -> bool: + def __eq__(self, other: 'DocumentClassifier') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParams') -> bool: + def __ne__(self, other: 'DocumentClassifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DefaultQueryParamsPassages(): +class DocumentClassifierEnrichment(): """ - Default settings configuration for passage search options. + An object that describes enrichments that are applied to the training and test data + that is used by the document classifier. - :attr bool enabled: (optional) When `true`, a passage search is performed by - default. - :attr int count: (optional) The number of passages to return. - :attr List[str] fields: (optional) An array of field names to perform the - passage search on. - :attr int characters: (optional) The approximate number of characters that each - returned passage will contain. - :attr bool per_document: (optional) When `true` the number of passages that can - be returned from a single document is restricted to the *max_per_document* - value. - :attr int max_per_document: (optional) The default maximum number of passages - that can be taken from a single document as the result of a passage query. + :attr str enrichment_id: A unique identifier of the enrichment. + :attr List[str] fields: An array of field names where the enrichment is applied. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - fields: List[str] = None, - characters: int = None, - per_document: bool = None, - max_per_document: int = None) -> None: + def __init__(self, enrichment_id: str, fields: List[str]) -> None: """ - Initialize a DefaultQueryParamsPassages object. + Initialize a DocumentClassifierEnrichment object. - :param bool enabled: (optional) When `true`, a passage search is performed - by default. - :param int count: (optional) The number of passages to return. - :param List[str] fields: (optional) An array of field names to perform the - passage search on. - :param int characters: (optional) The approximate number of characters that - each returned passage will contain. - :param bool per_document: (optional) When `true` the number of passages - that can be returned from a single document is restricted to the - *max_per_document* value. - :param int max_per_document: (optional) The default maximum number of - passages that can be taken from a single document as the result of a - passage query. + :param str enrichment_id: A unique identifier of the enrichment. + :param List[str] fields: An array of field names where the enrichment is + applied. """ - self.enabled = enabled - self.count = count + self.enrichment_id = enrichment_id self.fields = fields - self.characters = characters - self.per_document = per_document - self.max_per_document = max_per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': - """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierEnrichment': + """Initialize a DocumentClassifierEnrichment object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + else: + raise ValueError( + 'Required property \'enrichment_id\' not present in DocumentClassifierEnrichment JSON' + ) if 'fields' in _dict: args['fields'] = _dict.get('fields') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') + else: + raise ValueError( + 'Required property \'fields\' not present in DocumentClassifierEnrichment JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + """Initialize a DocumentClassifierEnrichment object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = self.fields - if hasattr(self, 'characters') and self.characters is not None: - _dict['characters'] = self.characters - if hasattr(self, 'per_document') and self.per_document is not None: - _dict['per_document'] = self.per_document - if hasattr(self, - 'max_per_document') and self.max_per_document is not None: - _dict['max_per_document'] = self.max_per_document + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields return _dict def _to_dict(self): @@ -3192,64 +5709,160 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsPassages object.""" + """Return a `str` version of this DocumentClassifierEnrichment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: + def __eq__(self, other: 'DocumentClassifierEnrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: + def __ne__(self, other: 'DocumentClassifierEnrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DefaultQueryParamsSuggestedRefinements(): - """ - Object that contains suggested refinement settings. Available with Premium plans only. - - :attr bool enabled: (optional) When `true`, suggested refinements for the query - are returned by default. - :attr int count: (optional) The number of suggested refinements to return by - default. +class DocumentClassifierModel(): + """ + Information about a document classifier model. + + :attr str model_id: (optional) A unique identifier of the document classifier + model. + :attr str name: A human-readable name of the document classifier model. + :attr str description: (optional) A description of the document classifier + model. + :attr datetime created: (optional) The date that the document classifier model + was created. + :attr datetime updated: (optional) The date that the document classifier model + was last updated. + :attr str training_data_file: (optional) Name of the CSV file that contains the + training data that is used to train the document classifier model. + :attr str test_data_file: (optional) Name of the CSV file that contains data + that is used to test the document classifier model. If no test data is provided, + a subset of the training data is used for testing purposes. + :attr str status: (optional) The status of the training run. + :attr ClassifierModelEvaluation evaluation: (optional) An object that contains + information about a trained document classifier model. + :attr str enrichment_id: (optional) A unique identifier of the enrichment that + is generated by this document classifier model. + :attr datetime deployed_at: (optional) The date that the document classifier + model was deployed. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: - """ - Initialize a DefaultQueryParamsSuggestedRefinements object. - - :param bool enabled: (optional) When `true`, suggested refinements for the - query are returned by default. - :param int count: (optional) The number of suggested refinements to return - by default. - """ - self.enabled = enabled - self.count = count + def __init__(self, + name: str, + *, + model_id: str = None, + description: str = None, + created: datetime = None, + updated: datetime = None, + training_data_file: str = None, + test_data_file: str = None, + status: str = None, + evaluation: 'ClassifierModelEvaluation' = None, + enrichment_id: str = None, + deployed_at: datetime = None) -> None: + """ + Initialize a DocumentClassifierModel object. + + :param str name: A human-readable name of the document classifier model. + :param str description: (optional) A description of the document classifier + model. + :param str training_data_file: (optional) Name of the CSV file that + contains the training data that is used to train the document classifier + model. + :param str test_data_file: (optional) Name of the CSV file that contains + data that is used to test the document classifier model. If no test data is + provided, a subset of the training data is used for testing purposes. + :param str status: (optional) The status of the training run. + :param ClassifierModelEvaluation evaluation: (optional) An object that + contains information about a trained document classifier model. + :param str enrichment_id: (optional) A unique identifier of the enrichment + that is generated by this document classifier model. + """ + self.model_id = model_id + self.name = name + self.description = description + self.created = created + self.updated = updated + self.training_data_file = training_data_file + self.test_data_file = test_data_file + self.status = status + self.evaluation = evaluation + self.enrichment_id = enrichment_id + self.deployed_at = deployed_at @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': - """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModel': + """Initialize a DocumentClassifierModel object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if 'model_id' in _dict: + args['model_id'] = _dict.get('model_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in DocumentClassifierModel JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + if 'training_data_file' in _dict: + args['training_data_file'] = _dict.get('training_data_file') + if 'test_data_file' in _dict: + args['test_data_file'] = _dict.get('test_data_file') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'evaluation' in _dict: + args['evaluation'] = ClassifierModelEvaluation.from_dict( + _dict.get('evaluation')) + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'deployed_at' in _dict: + args['deployed_at'] = string_to_datetime(_dict.get('deployed_at')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + """Initialize a DocumentClassifierModel object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count + if hasattr(self, 'model_id') and getattr(self, 'model_id') is not None: + _dict['model_id'] = getattr(self, 'model_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr( + self, + 'training_data_file') and self.training_data_file is not None: + _dict['training_data_file'] = self.training_data_file + if hasattr(self, 'test_data_file') and self.test_data_file is not None: + _dict['test_data_file'] = self.test_data_file + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'evaluation') and self.evaluation is not None: + if isinstance(self.evaluation, dict): + _dict['evaluation'] = self.evaluation + else: + _dict['evaluation'] = self.evaluation.to_dict() + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'deployed_at') and getattr(self, + 'deployed_at') is not None: + _dict['deployed_at'] = datetime_to_string( + getattr(self, 'deployed_at')) return _dict def _to_dict(self): @@ -3257,76 +5870,74 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" + """Return a `str` version of this DocumentClassifierModel object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: + def __eq__(self, other: 'DocumentClassifierModel') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: + def __ne__(self, other: 'DocumentClassifierModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The status of the training run. + """ + TRAINING = 'training' + AVAILABLE = 'available' + FAILED = 'failed' + -class DefaultQueryParamsTableResults(): +class DocumentClassifierModels(): """ - Default project query settings for table results. + An object that contains a list of document classifier model definitions. - :attr bool enabled: (optional) When `true`, a table results for the query are - returned by default. - :attr int count: (optional) The number of table results to return by default. - :attr int per_document: (optional) The number of table results to include in - each result document. + :attr List[DocumentClassifierModel] models: (optional) An array of document + classifier model definitions. """ def __init__(self, *, - enabled: bool = None, - count: int = None, - per_document: int = None) -> None: + models: List['DocumentClassifierModel'] = None) -> None: """ - Initialize a DefaultQueryParamsTableResults object. + Initialize a DocumentClassifierModels object. - :param bool enabled: (optional) When `true`, a table results for the query - are returned by default. - :param int count: (optional) The number of table results to return by - default. - :param int per_document: (optional) The number of table results to include - in each result document. + :param List[DocumentClassifierModel] models: (optional) An array of + document classifier model definitions. """ - self.enabled = enabled - self.count = count - self.per_document = per_document + self.models = models @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': - """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModels': + """Initialize a DocumentClassifierModels object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') + if 'models' in _dict: + args['models'] = [ + DocumentClassifierModel.from_dict(v) + for v in _dict.get('models') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" + """Initialize a DocumentClassifierModels object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'per_document') and self.per_document is not None: - _dict['per_document'] = self.per_document + if hasattr(self, 'models') and self.models is not None: + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -3334,62 +5945,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsTableResults object.""" + """Return a `str` version of this DocumentClassifierModels object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsTableResults') -> bool: + def __eq__(self, other: 'DocumentClassifierModels') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: + def __ne__(self, other: 'DocumentClassifierModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DeleteDocumentResponse(): +class DocumentClassifiers(): """ - Information returned when a document is deleted. + An object that contains a list of document classifier definitions. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the - status deleted. + :attr List[DocumentClassifier] classifiers: (optional) An array of document + classifier definitions. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__(self, + *, + classifiers: List['DocumentClassifier'] = None) -> None: """ - Initialize a DeleteDocumentResponse object. + Initialize a DocumentClassifiers object. - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. + :param List[DocumentClassifier] classifiers: (optional) An array of + document classifier definitions. """ - self.document_id = document_id - self.status = status + self.classifiers = classifiers @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifiers': + """Initialize a DocumentClassifiers object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if 'classifiers' in _dict: + args['classifiers'] = [ + DocumentClassifier.from_dict(v) + for v in _dict.get('classifiers') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + """Initialize a DocumentClassifiers object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'classifiers') and self.classifiers is not None: + classifiers_list = [] + for v in self.classifiers: + if isinstance(v, dict): + classifiers_list.append(v) + else: + classifiers_list.append(v.to_dict()) + _dict['classifiers'] = classifiers_list return _dict def _to_dict(self): @@ -3397,74 +6012,163 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DeleteDocumentResponse object.""" + """Return a `str` version of this DocumentClassifiers object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DeleteDocumentResponse') -> bool: + def __eq__(self, other: 'DocumentClassifiers') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DeleteDocumentResponse') -> bool: + def __ne__(self, other: 'DocumentClassifiers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - DELETED = 'deleted' - -class DocumentAccepted(): +class DocumentDetails(): """ - Information returned after an uploaded document is accepted. + Information about a document. - :attr str document_id: (optional) The unique identifier of the ingested - document. - :attr str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. + :attr str document_id: (optional) The unique identifier of the document. + :attr datetime created: (optional) Date and time that the document is added to + the collection. For a child document, the date and time when the process that + generates the child document runs. The date-time format is + `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :attr datetime updated: (optional) Date and time that the document is finished + being processed and is indexed. This date changes whenever the document is + reprocessed, including for enrichment changes. The date-time format is + `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :attr str status: (optional) The status of the ingestion of the document. The + possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because of an + error. + * `pending`: The document is uploaded, but the ingestion process is not started. + * `processing`: Ingestion is in progress. + :attr List[Notice] notices: (optional) Array of JSON objects for notices, + meaning warning or error messages, that are produced by the document ingestion + process. The array does not include notices that are produced for child + documents that are generated when a document is processed. + :attr DocumentDetailsChildren children: (optional) Information about the child + documents that are generated from a single document during ingestion or other + processing. + :attr str filename: (optional) Name of the original source file (if available). + :attr str file_type: (optional) The type of the original source file, such as + `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. + :attr str sha256: (optional) The SHA-256 hash of the original source file. The + hash is formatted as a hexadecimal string. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: - """ - Initialize a DocumentAccepted object. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. + def __init__(self, + *, + document_id: str = None, + created: datetime = None, + updated: datetime = None, + status: str = None, + notices: List['Notice'] = None, + children: 'DocumentDetailsChildren' = None, + filename: str = None, + file_type: str = None, + sha256: str = None) -> None: + """ + Initialize a DocumentDetails object. + + :param str status: (optional) The status of the ingestion of the document. + The possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because + of an error. + * `pending`: The document is uploaded, but the ingestion process is not + started. + * `processing`: Ingestion is in progress. + :param List[Notice] notices: (optional) Array of JSON objects for notices, + meaning warning or error messages, that are produced by the document + ingestion process. The array does not include notices that are produced for + child documents that are generated when a document is processed. + :param DocumentDetailsChildren children: (optional) Information about the + child documents that are generated from a single document during ingestion + or other processing. + :param str filename: (optional) Name of the original source file (if + available). + :param str file_type: (optional) The type of the original source file, such + as `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. + :param str sha256: (optional) The SHA-256 hash of the original source file. + The hash is formatted as a hexadecimal string. """ self.document_id = document_id + self.created = created + self.updated = updated self.status = status + self.notices = notices + self.children = children + self.filename = filename + self.file_type = file_type + self.sha256 = sha256 @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentDetails': + """Initialize a DocumentDetails object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) if 'status' in _dict: args['status'] = _dict.get('status') + if 'notices' in _dict: + args['notices'] = [ + Notice.from_dict(v) for v in _dict.get('notices') + ] + if 'children' in _dict: + args['children'] = DocumentDetailsChildren.from_dict( + _dict.get('children')) + if 'filename' in _dict: + args['filename'] = _dict.get('filename') + if 'file_type' in _dict: + args['file_type'] = _dict.get('file_type') + if 'sha256' in _dict: + args['sha256'] = _dict.get('sha256') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAccepted object from a json dictionary.""" + """Initialize a DocumentDetails object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id + if hasattr(self, 'document_id') and getattr(self, + 'document_id') is not None: + _dict['document_id'] = getattr(self, 'document_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status + if hasattr(self, 'notices') and self.notices is not None: + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list + if hasattr(self, 'children') and self.children is not None: + if isinstance(self.children, dict): + _dict['children'] = self.children + else: + _dict['children'] = self.children.to_dict() + if hasattr(self, 'filename') and self.filename is not None: + _dict['filename'] = self.filename + if hasattr(self, 'file_type') and self.file_type is not None: + _dict['file_type'] = self.file_type + if hasattr(self, 'sha256') and self.sha256 is not None: + _dict['sha256'] = self.sha256 return _dict def _to_dict(self): @@ -3472,85 +6176,80 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAccepted object.""" + """Return a `str` version of this DocumentDetails object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DocumentAccepted') -> bool: + def __eq__(self, other: 'DocumentDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DocumentAccepted') -> bool: + def __ne__(self, other: 'DocumentDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class StatusEnum(str, Enum): """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. + The status of the ingestion of the document. The possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because of an + error. + * `pending`: The document is uploaded, but the ingestion process is not started. + * `processing`: Ingestion is in progress. """ - PROCESSING = 'processing' + AVAILABLE = 'available' + FAILED = 'failed' PENDING = 'pending' + PROCESSING = 'processing' -class DocumentAttribute(): +class DocumentDetailsChildren(): """ - List of document attributes. + Information about the child documents that are generated from a single document during + ingestion or other processing. - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr TableElementLocation location: (optional) The numeric location of the - identified element in the document, represented with two integers labeled - `begin` and `end`. + :attr bool have_notices: (optional) Indicates whether the child documents have + any notices. The value is `false` if the document does not have child documents. + :attr int count: (optional) Number of child documents. The value is `0` when + processing of the document doesn't generate any child documents. """ - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__(self, *, have_notices: bool = None, count: int = None) -> None: """ - Initialize a DocumentAttribute object. + Initialize a DocumentDetailsChildren object. - :param str type: (optional) The type of attribute. - :param str text: (optional) The text associated with the attribute. - :param TableElementLocation location: (optional) The numeric location of - the identified element in the document, represented with two integers - labeled `begin` and `end`. + :param bool have_notices: (optional) Indicates whether the child documents + have any notices. The value is `false` if the document does not have child + documents. + :param int count: (optional) Number of child documents. The value is `0` + when processing of the document doesn't generate any child documents. """ - self.type = type - self.text = text - self.location = location + self.have_notices = have_notices + self.count = count @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': - """Initialize a DocumentAttribute object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentDetailsChildren': + """Initialize a DocumentDetailsChildren object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if 'have_notices' in _dict: + args['have_notices'] = _dict.get('have_notices') + if 'count' in _dict: + args['count'] = _dict.get('count') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAttribute object from a json dictionary.""" + """Initialize a DocumentDetailsChildren object from a json dictionary.""" return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'have_notices') and self.have_notices is not None: + _dict['have_notices'] = self.have_notices + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count return _dict def _to_dict(self): @@ -3558,16 +6257,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAttribute object.""" + """Return a `str` version of this DocumentDetailsChildren object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DocumentAttribute') -> bool: + def __eq__(self, other: 'DocumentDetailsChildren') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'DocumentAttribute') -> bool: + def __ne__(self, other: 'DocumentDetailsChildren') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3643,7 +6342,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -3676,6 +6378,7 @@ class TypeEnum(str, Enum): UIMA_ANNOTATOR = 'uima_annotator' RULE_BASED = 'rule_based' WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + CLASSIFIER = 'classifier' class EnrichmentOptions(): @@ -3685,17 +6388,35 @@ class EnrichmentOptions(): Enrichments method. :attr List[str] languages: (optional) An array of supported languages for this - enrichment. Required when `type` is `dictionary`. Optional when `type` is - `rule_based`. Not valid when creating any other type of enrichment. + enrichment. When creating an enrichment, only specify a language that is used by + the model or in the dictionary. Required when **type** is `dictionary`. Optional + when **type** is `rule_based`. Not valid when creating any other type of + enrichment. :attr str entity_type: (optional) The name of the entity type. This value is - used as the field name in the index. Required when `type` is `dictionary` or + used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. :attr str regular_expression: (optional) The regular expression to apply for - this enrichment. Required when `type` is `regular_expression`. Not valid when + this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. :attr str result_field: (optional) The name of the result document field that - this enrichment creates. Required when `type` is `rule_based`. Not valid when - creating any other type of enrichment. + this enrichment creates. Required when **type** is `rule_based` or `classifier`. + Not valid when creating any other type of enrichment. + :attr str classifier_id: (optional) A unique identifier of the document + classifier. Required when **type** is `classifier`. Not valid when creating any + other type of enrichment. + :attr str model_id: (optional) A unique identifier of the document classifier + model. Required when **type** is `classifier`. Not valid when creating any other + type of enrichment. + :attr float confidence_threshold: (optional) Specifies a threshold. Only classes + with evaluation confidence scores that are higher than the specified threshold + are included in the output. Optional when **type** is `classifier`. Not valid + when creating any other type of enrichment. + :attr int top_k: (optional) Evaluates only the classes that fall in the top set + of results when ranked by confidence. For example, if set to `5`, then the top + five classes for each document are evaluated. If set to 0, the + **confidence_threshold** is used to determine the predicted classes. Optional + when **type** is `classifier`. Not valid when creating any other type of + enrichment. """ def __init__(self, @@ -3703,28 +6424,54 @@ def __init__(self, languages: List[str] = None, entity_type: str = None, regular_expression: str = None, - result_field: str = None) -> None: + result_field: str = None, + classifier_id: str = None, + model_id: str = None, + confidence_threshold: float = None, + top_k: int = None) -> None: """ Initialize a EnrichmentOptions object. :param List[str] languages: (optional) An array of supported languages for - this enrichment. Required when `type` is `dictionary`. Optional when `type` - is `rule_based`. Not valid when creating any other type of enrichment. + this enrichment. When creating an enrichment, only specify a language that + is used by the model or in the dictionary. Required when **type** is + `dictionary`. Optional when **type** is `rule_based`. Not valid when + creating any other type of enrichment. :param str entity_type: (optional) The name of the entity type. This value - is used as the field name in the index. Required when `type` is + is used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. :param str regular_expression: (optional) The regular expression to apply - for this enrichment. Required when `type` is `regular_expression`. Not + for this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. :param str result_field: (optional) The name of the result document field - that this enrichment creates. Required when `type` is `rule_based`. Not - valid when creating any other type of enrichment. + that this enrichment creates. Required when **type** is `rule_based` or + `classifier`. Not valid when creating any other type of enrichment. + :param str classifier_id: (optional) A unique identifier of the document + classifier. Required when **type** is `classifier`. Not valid when creating + any other type of enrichment. + :param str model_id: (optional) A unique identifier of the document + classifier model. Required when **type** is `classifier`. Not valid when + creating any other type of enrichment. + :param float confidence_threshold: (optional) Specifies a threshold. Only + classes with evaluation confidence scores that are higher than the + specified threshold are included in the output. Optional when **type** is + `classifier`. Not valid when creating any other type of enrichment. + :param int top_k: (optional) Evaluates only the classes that fall in the + top set of results when ranked by confidence. For example, if set to `5`, + then the top five classes for each document are evaluated. If set to 0, the + **confidence_threshold** is used to determine the predicted classes. + Optional when **type** is `classifier`. Not valid when creating any other + type of enrichment. """ self.languages = languages self.entity_type = entity_type self.regular_expression = regular_expression self.result_field = result_field + self.classifier_id = classifier_id + self.model_id = model_id + self.confidence_threshold = confidence_threshold + self.top_k = top_k @classmethod def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': @@ -3738,6 +6485,14 @@ def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': args['regular_expression'] = _dict.get('regular_expression') if 'result_field' in _dict: args['result_field'] = _dict.get('result_field') + if 'classifier_id' in _dict: + args['classifier_id'] = _dict.get('classifier_id') + if 'model_id' in _dict: + args['model_id'] = _dict.get('model_id') + if 'confidence_threshold' in _dict: + args['confidence_threshold'] = _dict.get('confidence_threshold') + if 'top_k' in _dict: + args['top_k'] = _dict.get('top_k') return cls(**args) @classmethod @@ -3758,6 +6513,15 @@ def to_dict(self) -> Dict: _dict['regular_expression'] = self.regular_expression if hasattr(self, 'result_field') and self.result_field is not None: _dict['result_field'] = self.result_field + if hasattr(self, 'classifier_id') and self.classifier_id is not None: + _dict['classifier_id'] = self.classifier_id + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'top_k') and self.top_k is not None: + _dict['top_k'] = self.top_k return _dict def _to_dict(self): @@ -3802,7 +6566,7 @@ def from_dict(cls, _dict: Dict) -> 'Enrichments': args = {} if 'enrichments' in _dict: args['enrichments'] = [ - Enrichment.from_dict(x) for x in _dict.get('enrichments') + Enrichment.from_dict(v) for v in _dict.get('enrichments') ] return cls(**args) @@ -3815,7 +6579,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list return _dict def _to_dict(self): @@ -3837,6 +6607,175 @@ def __ne__(self, other: 'Enrichments') -> bool: return not self == other +class Expansion(): + """ + An expansion definition. Each object respresents one set of expandable strings. For + example, you could have expansions for the word `hot` in one object, and expansions + for the word `cold` in another. Follow these guidelines when you add terms: + * Specify the terms in lowercase. Lowercase terms expand to uppercase. + * Multiword terms are supported only in bidirectional expansions. + * Do not specify a term that is specified in the stop words list for the collection. + + :attr List[str] input_terms: (optional) A list of terms that will be expanded + for this expansion. If specified, only the items in this list are expanded. + :attr List[str] expanded_terms: A list of terms that this expansion will be + expanded to. If specified without **input_terms**, the list also functions as + the input term list. + """ + + def __init__(self, + expanded_terms: List[str], + *, + input_terms: List[str] = None) -> None: + """ + Initialize a Expansion object. + + :param List[str] expanded_terms: A list of terms that this expansion will + be expanded to. If specified without **input_terms**, the list also + functions as the input term list. + :param List[str] input_terms: (optional) A list of terms that will be + expanded for this expansion. If specified, only the items in this list are + expanded. + """ + self.input_terms = input_terms + self.expanded_terms = expanded_terms + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Expansion': + """Initialize a Expansion object from a json dictionary.""" + args = {} + if 'input_terms' in _dict: + args['input_terms'] = _dict.get('input_terms') + if 'expanded_terms' in _dict: + args['expanded_terms'] = _dict.get('expanded_terms') + else: + raise ValueError( + 'Required property \'expanded_terms\' not present in Expansion JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansion object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'input_terms') and self.input_terms is not None: + _dict['input_terms'] = self.input_terms + if hasattr(self, 'expanded_terms') and self.expanded_terms is not None: + _dict['expanded_terms'] = self.expanded_terms + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Expansion object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Expansion') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Expansion') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Expansions(): + """ + The query expansion definitions for the specified collection. + + :attr List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms that + will be expanded into other terms. Each expansion object can be configured as + `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to include + all expanded terms. For example, a query for `ibm` expands to `ibm OR + international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced by + the terms in `expanded_terms`. For example, a query for the often misused term + `on premise` is converted to `on premises OR on-premises` and does not contain + the original term. If you want an input term to be included in the query, then + repeat the input term in the expanded terms list. + """ + + def __init__(self, expansions: List['Expansion']) -> None: + """ + Initialize a Expansions object. + + :param List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to + include all expanded terms. For example, a query for `ibm` expands to `ibm + OR international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced + by the terms in `expanded_terms`. For example, a query for the often + misused term `on premise` is converted to `on premises OR on-premises` and + does not contain the original term. If you want an input term to be + included in the query, then repeat the input term in the expanded terms + list. + """ + self.expansions = expansions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Expansions': + """Initialize a Expansions object from a json dictionary.""" + args = {} + if 'expansions' in _dict: + args['expansions'] = [ + Expansion.from_dict(v) for v in _dict.get('expansions') + ] + else: + raise ValueError( + 'Required property \'expansions\' not present in Expansions JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'expansions') and self.expansions is not None: + expansions_list = [] + for v in self.expansions: + if isinstance(v, dict): + expansions_list.append(v) + else: + expansions_list.append(v.to_dict()) + _dict['expansions'] = expansions_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Expansions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Expansions') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Expansions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Field(): """ Object that contains field details. @@ -3939,28 +6878,246 @@ def __init__(self, *, collections: List['Collection'] = None) -> None: :param List[Collection] collections: (optional) An array that contains information about each collection in the project. """ - self.collections = collections + self.collections = collections + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': + """Initialize a ListCollectionsResponse object from a json dictionary.""" + args = {} + if 'collections' in _dict: + args['collections'] = [ + Collection.from_dict(v) for v in _dict.get('collections') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionsResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collections') and self.collections is not None: + collections_list = [] + for v in self.collections: + if isinstance(v, dict): + collections_list.append(v) + else: + collections_list.append(v.to_dict()) + _dict['collections'] = collections_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ListCollectionsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListCollectionsResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ListCollectionsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListDocumentsResponse(): + """ + Response object that contains an array of documents. + + :attr int matching_results: (optional) The number of matching results for the + document query. + :attr List[DocumentDetails] documents: (optional) An array that lists the + documents in a collection. Only the document ID of each document is returned in + the list. You can use the [Get document](#getdocument) method to get more + information about an individual document. + """ + + def __init__(self, + *, + matching_results: int = None, + documents: List['DocumentDetails'] = None) -> None: + """ + Initialize a ListDocumentsResponse object. + + :param int matching_results: (optional) The number of matching results for + the document query. + :param List[DocumentDetails] documents: (optional) An array that lists the + documents in a collection. Only the document ID of each document is + returned in the list. You can use the [Get document](#getdocument) method + to get more information about an individual document. + """ + self.matching_results = matching_results + self.documents = documents + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListDocumentsResponse': + """Initialize a ListDocumentsResponse object from a json dictionary.""" + args = {} + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'documents' in _dict: + args['documents'] = [ + DocumentDetails.from_dict(v) for v in _dict.get('documents') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListDocumentsResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'documents') and self.documents is not None: + documents_list = [] + for v in self.documents: + if isinstance(v, dict): + documents_list.append(v) + else: + documents_list.append(v.to_dict()) + _dict['documents'] = documents_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ListDocumentsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListDocumentsResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ListDocumentsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListFieldsResponse(): + """ + The list of fetched fields. + The fields are returned using a fully qualified name format, however, the format + differs slightly from that used by the query operations. + * Fields which contain nested objects are assigned a type of "nested". + * Fields which belong to a nested object are prefixed with `.properties` (for + example, `warnings.properties.severity` means that the `warnings` object has a + property called `severity`). + + :attr List[Field] fields: (optional) An array that contains information about + each field in the collections. + """ + + def __init__(self, *, fields: List['Field'] = None) -> None: + """ + Initialize a ListFieldsResponse object. + + :param List[Field] fields: (optional) An array that contains information + about each field in the collections. + """ + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': + """Initialize a ListFieldsResponse object from a json dictionary.""" + args = {} + if 'fields' in _dict: + args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListFieldsResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'fields') and self.fields is not None: + fields_list = [] + for v in self.fields: + if isinstance(v, dict): + fields_list.append(v) + else: + fields_list.append(v.to_dict()) + _dict['fields'] = fields_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ListFieldsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListFieldsResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ListFieldsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListProjectsResponse(): + """ + A list of projects in this instance. + + :attr List[ProjectListDetails] projects: (optional) An array of project details. + """ + + def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: + """ + Initialize a ListProjectsResponse object. + + :param List[ProjectListDetails] projects: (optional) An array of project + details. + """ + self.projects = projects @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': - """Initialize a ListCollectionsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': + """Initialize a ListProjectsResponse object from a json dictionary.""" args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(x) for x in _dict.get('collections') + if 'projects' in _dict: + args['projects'] = [ + ProjectListDetails.from_dict(v) for v in _dict.get('projects') ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListCollectionsResponse object from a json dictionary.""" + """Initialize a ListProjectsResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] + if hasattr(self, 'projects') and self.projects is not None: + projects_list = [] + for v in self.projects: + if isinstance(v, dict): + projects_list.append(v) + else: + projects_list.append(v.to_dict()) + _dict['projects'] = projects_list return _dict def _to_dict(self): @@ -3968,61 +7125,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListCollectionsResponse object.""" + """Return a `str` version of this ListProjectsResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListCollectionsResponse') -> bool: + def __eq__(self, other: 'ListProjectsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListCollectionsResponse') -> bool: + def __ne__(self, other: 'ListProjectsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ListFieldsResponse(): +class ModelEvaluationMacroAverage(): """ - The list of fetched fields. - The fields are returned using a fully qualified name format, however, the format - differs slightly from that used by the query operations. - * Fields which contain nested objects are assigned a type of "nested". - * Fields which belong to a nested object are prefixed with `.properties` (for - example, `warnings.properties.severity` means that the `warnings` object has a - property called `severity`). + A macro-average computes metric independently for each class and then takes the + average. Class refers to the classification label that is specified in the + **answer_field**. - :attr List[Field] fields: (optional) An array that contains information about - each field in the collections. + :attr float precision: A metric that measures how many of the overall documents + are classified correctly. + :attr float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :attr float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__(self, precision: float, recall: float, f1: float) -> None: """ - Initialize a ListFieldsResponse object. + Initialize a ModelEvaluationMacroAverage object. - :param List[Field] fields: (optional) An array that contains information - about each field in the collections. + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. """ - self.fields = fields + self.precision = precision + self.recall = recall + self.f1 = f1 @classmethod - def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': - """Initialize a ListFieldsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMacroAverage': + """Initialize a ModelEvaluationMacroAverage object from a json dictionary.""" args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] + if 'precision' in _dict: + args['precision'] = _dict.get('precision') + else: + raise ValueError( + 'Required property \'precision\' not present in ModelEvaluationMacroAverage JSON' + ) + if 'recall' in _dict: + args['recall'] = _dict.get('recall') + else: + raise ValueError( + 'Required property \'recall\' not present in ModelEvaluationMacroAverage JSON' + ) + if 'f1' in _dict: + args['f1'] = _dict.get('f1') + else: + raise ValueError( + 'Required property \'f1\' not present in ModelEvaluationMacroAverage JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListFieldsResponse object from a json dictionary.""" + """Initialize a ModelEvaluationMacroAverage object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x.to_dict() for x in self.fields] + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 return _dict def _to_dict(self): @@ -4030,56 +7217,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListFieldsResponse object.""" + """Return a `str` version of this ModelEvaluationMacroAverage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListFieldsResponse') -> bool: + def __eq__(self, other: 'ModelEvaluationMacroAverage') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListFieldsResponse') -> bool: + def __ne__(self, other: 'ModelEvaluationMacroAverage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ListProjectsResponse(): +class ModelEvaluationMicroAverage(): """ - A list of projects in this instance. + A micro-average aggregates the contributions of all classes to compute the average + metric. Classes refers to the classification labels that are specified in the + **answer_field**. - :attr List[ProjectListDetails] projects: (optional) An array of project details. + :attr float precision: A metric that measures how many of the overall documents + are classified correctly. + :attr float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :attr float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. """ - def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: + def __init__(self, precision: float, recall: float, f1: float) -> None: """ - Initialize a ListProjectsResponse object. + Initialize a ModelEvaluationMicroAverage object. - :param List[ProjectListDetails] projects: (optional) An array of project - details. + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. """ - self.projects = projects + self.precision = precision + self.recall = recall + self.f1 = f1 @classmethod - def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': - """Initialize a ListProjectsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMicroAverage': + """Initialize a ModelEvaluationMicroAverage object from a json dictionary.""" args = {} - if 'projects' in _dict: - args['projects'] = [ - ProjectListDetails.from_dict(x) for x in _dict.get('projects') - ] + if 'precision' in _dict: + args['precision'] = _dict.get('precision') + else: + raise ValueError( + 'Required property \'precision\' not present in ModelEvaluationMicroAverage JSON' + ) + if 'recall' in _dict: + args['recall'] = _dict.get('recall') + else: + raise ValueError( + 'Required property \'recall\' not present in ModelEvaluationMicroAverage JSON' + ) + if 'f1' in _dict: + args['f1'] = _dict.get('f1') + else: + raise ValueError( + 'Required property \'f1\' not present in ModelEvaluationMicroAverage JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListProjectsResponse object from a json dictionary.""" + """Initialize a ModelEvaluationMicroAverage object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'projects') and self.projects is not None: - _dict['projects'] = [x.to_dict() for x in self.projects] + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 return _dict def _to_dict(self): @@ -4087,16 +7309,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListProjectsResponse object.""" + """Return a `str` version of this ModelEvaluationMicroAverage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListProjectsResponse') -> bool: + def __eq__(self, other: 'ModelEvaluationMicroAverage') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ListProjectsResponse') -> bool: + def __ne__(self, other: 'ModelEvaluationMicroAverage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4108,7 +7330,8 @@ class Notice(): :attr str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, + include: + `index_failed`, `index_failed_too_many_requests`, `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, @@ -4118,7 +7341,7 @@ class Notice(): `smart_document_understanding_failed_warning`, `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete - list, other values might be returned. + list. Other values might be returned. :attr datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str document_id: (optional) Unique identifier of the document. @@ -4232,6 +7455,111 @@ class SeverityEnum(str, Enum): ERROR = 'error' +class PerClassModelEvaluation(): + """ + An object that measures the metrics from a training run for each classification label + separately. + + :attr str name: Class name. Each class name is derived from a value in the + **answer_field**. + :attr float precision: A metric that measures how many of the overall documents + are classified correctly. + :attr float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :attr float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. + """ + + def __init__(self, name: str, precision: float, recall: float, + f1: float) -> None: + """ + Initialize a PerClassModelEvaluation object. + + :param str name: Class name. Each class name is derived from a value in the + **answer_field**. + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. + """ + self.name = name + self.precision = precision + self.recall = recall + self.f1 = f1 + + @classmethod + def from_dict(cls, _dict: Dict) -> 'PerClassModelEvaluation': + """Initialize a PerClassModelEvaluation object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in PerClassModelEvaluation JSON' + ) + if 'precision' in _dict: + args['precision'] = _dict.get('precision') + else: + raise ValueError( + 'Required property \'precision\' not present in PerClassModelEvaluation JSON' + ) + if 'recall' in _dict: + args['recall'] = _dict.get('recall') + else: + raise ValueError( + 'Required property \'recall\' not present in PerClassModelEvaluation JSON' + ) + if 'f1' in _dict: + args['f1'] = _dict.get('f1') + else: + raise ValueError( + 'Required property \'f1\' not present in PerClassModelEvaluation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a PerClassModelEvaluation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this PerClassModelEvaluation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'PerClassModelEvaluation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'PerClassModelEvaluation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ProjectDetails(): """ Detailed information about the specified project. @@ -4269,8 +7597,6 @@ def __init__(self, project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: - (optional) Relevancy training status information for this project. :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ @@ -4317,19 +7643,26 @@ def to_dict(self) -> Dict: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'relevancy_training_status' - ) and self.relevancy_training_status is not None: - _dict[ - 'relevancy_training_status'] = self.relevancy_training_status.to_dict( - ) + if hasattr(self, 'relevancy_training_status') and getattr( + self, 'relevancy_training_status') is not None: + if isinstance(getattr(self, 'relevancy_training_status'), dict): + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status') + else: + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status').to_dict() if hasattr(self, 'collection_count') and getattr( self, 'collection_count') is not None: _dict['collection_count'] = getattr(self, 'collection_count') if hasattr(self, 'default_query_parameters' ) and self.default_query_parameters is not None: - _dict[ - 'default_query_parameters'] = self.default_query_parameters.to_dict( - ) + if isinstance(self.default_query_parameters, dict): + _dict[ + 'default_query_parameters'] = self.default_query_parameters + else: + _dict[ + 'default_query_parameters'] = self.default_query_parameters.to_dict( + ) return _dict def _to_dict(self): @@ -4399,8 +7732,6 @@ def __init__(self, project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: - (optional) Relevancy training status information for this project. """ self.project_id = project_id self.name = name @@ -4441,11 +7772,14 @@ def to_dict(self) -> Dict: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'relevancy_training_status' - ) and self.relevancy_training_status is not None: - _dict[ - 'relevancy_training_status'] = self.relevancy_training_status.to_dict( - ) + if hasattr(self, 'relevancy_training_status') and getattr( + self, 'relevancy_training_status') is not None: + if isinstance(getattr(self, 'relevancy_training_status'), dict): + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status') + else: + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status').to_dict() if hasattr(self, 'collection_count') and getattr( self, 'collection_count') is not None: _dict['collection_count'] = getattr(self, 'collection_count') @@ -4629,22 +7963,30 @@ def __ne__(self, class QueryAggregation(): """ - An abstract aggregation type produced by Discovery to analyze the input provided. + An object that defines how to aggregate query results. - :attr str type: The type of aggregation command used. Options include: term, - histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and - top_hits. """ - def __init__(self, type: str) -> None: + def __init__(self) -> None: """ Initialize a QueryAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. """ - self.type = type + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) + raise Exception(msg) @classmethod def from_dict(cls, _dict: Dict) -> 'QueryAggregation': @@ -4652,60 +7994,47 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryAggregation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): + msg = ( + "Cannot convert dictionary into an instance of base class 'QueryAggregation'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): """Initialize a QueryAggregation object from a json dictionary.""" return cls.from_dict(_dict) - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryAggregation') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'QueryAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} - mapping['term'] = 'QueryTermAggregation' - mapping['histogram'] = 'QueryHistogramAggregation' - mapping['timeslice'] = 'QueryTimesliceAggregation' - mapping['nested'] = 'QueryNestedAggregation' - mapping['filter'] = 'QueryFilterAggregation' - mapping['min'] = 'QueryCalculationAggregation' - mapping['max'] = 'QueryCalculationAggregation' - mapping['sum'] = 'QueryCalculationAggregation' - mapping['average'] = 'QueryCalculationAggregation' - mapping['unique_count'] = 'QueryCalculationAggregation' - mapping['top_hits'] = 'QueryTopHitsAggregation' - mapping['group_by'] = 'QueryGroupByAggregation' + mapping['term'] = 'QueryAggregationQueryTermAggregation' + mapping['group_by'] = 'QueryAggregationQueryGroupByAggregation' + mapping['histogram'] = 'QueryAggregationQueryHistogramAggregation' + mapping['timeslice'] = 'QueryAggregationQueryTimesliceAggregation' + mapping['nested'] = 'QueryAggregationQueryNestedAggregation' + mapping['filter'] = 'QueryAggregationQueryFilterAggregation' + mapping['min'] = 'QueryAggregationQueryCalculationAggregation' + mapping['max'] = 'QueryAggregationQueryCalculationAggregation' + mapping['sum'] = 'QueryAggregationQueryCalculationAggregation' + mapping['average'] = 'QueryAggregationQueryCalculationAggregation' + mapping['unique_count'] = 'QueryAggregationQueryCalculationAggregation' + mapping['top_hits'] = 'QueryAggregationQueryTopHitsAggregation' + mapping['pair'] = 'QueryAggregationQueryPairAggregation' + mapping['trend'] = 'QueryAggregationQueryTrendAggregation' + mapping['topic'] = 'QueryAggregationQueryTopicAggregation' disc_value = _dict.get('type') if disc_value is None: raise ValueError( @@ -4723,19 +8052,22 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: class QueryGroupByAggregationResult(): """ - Top value result for the term aggregation. + Result group for the `group_by` aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this group. - :attr int total_matching_documents: (optional) The number of documents which - have the group as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr str key: The condition that is met by the documents in this group. For + example, `YEARTXT<2000`. + :attr int matching_results: Number of documents that meet the query and + condition. + :attr float relevancy: (optional) The relevancy for this group. Returned only if + `relevancy:true` is specified in the request. + :attr int total_matching_documents: (optional) Number of documents that meet the + condition in the whole set of documents in this collection. Returned only when + `relevancy:true` is specified in the request. + :attr float estimated_matching_results: (optional) The number of documents that + are estimated to match the query and condition. Returned only when + `relevancy:true` is specified in the request. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ def __init__(self, @@ -4744,30 +8076,31 @@ def __init__(self, *, relevancy: float = None, total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + estimated_matching_results: float = None, + aggregations: List[dict] = None) -> None: """ Initialize a QueryGroupByAggregationResult object. - :param str key: Value of the field with a non-zero frequency in the - document set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this group. - :param int total_matching_documents: (optional) The number of documents - which have the group as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str key: The condition that is met by the documents in this group. + For example, `YEARTXT<2000`. + :param int matching_results: Number of documents that meet the query and + condition. + :param float relevancy: (optional) The relevancy for this group. Returned + only if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents that + meet the condition in the whole set of documents in this collection. + Returned only when `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) The number of documents + that are estimated to match the query and condition. Returned only when + `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key = key self.matching_results = matching_results self.relevancy = relevancy self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents + self.estimated_matching_results = estimated_matching_results self.aggregations = aggregations @classmethod @@ -4791,13 +8124,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': if 'total_matching_documents' in _dict: args['total_matching_documents'] = _dict.get( 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') + if 'estimated_matching_results' in _dict: + args['estimated_matching_results'] = _dict.get( + 'estimated_matching_results') if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -4818,12 +8149,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'total_matching_documents' ) and self.total_matching_documents is not None: _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: + if hasattr(self, 'estimated_matching_results' + ) and self.estimated_matching_results is not None: _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents + 'estimated_matching_results'] = self.estimated_matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -4852,23 +8183,23 @@ class QueryHistogramAggregationResult(): :attr int key: The value of the upper bound for the numeric segment. :attr int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ def __init__(self, key: int, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + aggregations: List[dict] = None) -> None: """ Initialize a QueryHistogramAggregationResult object. :param int key: The value of the upper bound for the numeric segment. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key = key self.matching_results = matching_results @@ -4891,9 +8222,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -4910,7 +8239,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -4946,11 +8275,13 @@ class QueryLargePassages(): regardless of the document quality and returns them in a separate `passages` field in the response. :attr int max_per_document: (optional) Maximum number of passages to return per - document in the result. Ignored if `passages.per_document` is `false`. - :attr List[str] fields: (optional) A list of fields to extract passages from. If - this parameter is an empty list, then all root-level fields are included. + document in the result. Ignored if **passages.per_document** is `false`. + :attr List[str] fields: (optional) A list of fields to extract passages from. By + default, passages are extracted from the `text` and `title` fields only. If you + add this parameter and specify an empty list (`[]`) as its value, then the + service searches all root-level fields for suitable passages. :attr int count: (optional) The maximum number of passages to return. Ignored if - `passages.per_document` is `true`. + **passages.per_document** is `true`. :attr int characters: (optional) The approximate number of characters that any one passage will have. :attr bool find_answers: (optional) When true, `answer` objects are returned as @@ -4997,13 +8328,15 @@ def __init__(self, regardless of the document quality and returns them in a separate `passages` field in the response. :param int max_per_document: (optional) Maximum number of passages to - return per document in the result. Ignored if `passages.per_document` is + return per document in the result. Ignored if **passages.per_document** is `false`. :param List[str] fields: (optional) A list of fields to extract passages - from. If this parameter is an empty list, then all root-level fields are - included. + from. By default, passages are extracted from the `text` and `title` fields + only. If you add this parameter and specify an empty list (`[]`) as its + value, then the service searches all root-level fields for suitable + passages. :param int count: (optional) The maximum number of passages to return. - Ignored if `passages.per_document` is `true`. + Ignored if **passages.per_document** is `true`. :param int characters: (optional) The approximate number of characters that any one passage will have. :param bool find_answers: (optional) When true, `answer` objects are @@ -5050,20 +8383,115 @@ def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': args['max_per_document'] = _dict.get('max_per_document') if 'fields' in _dict: args['fields'] = _dict.get('fields') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'find_answers' in _dict: - args['find_answers'] = _dict.get('find_answers') - if 'max_answers_per_passage' in _dict: - args['max_answers_per_passage'] = _dict.get( - 'max_answers_per_passage') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'characters' in _dict: + args['characters'] = _dict.get('characters') + if 'find_answers' in _dict: + args['find_answers'] = _dict.get('find_answers') + if 'max_answers_per_passage' in _dict: + args['max_answers_per_passage'] = _dict.get( + 'max_answers_per_passage') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargePassages object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document + if hasattr(self, + 'max_per_document') and self.max_per_document is not None: + _dict['max_per_document'] = self.max_per_document + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'characters') and self.characters is not None: + _dict['characters'] = self.characters + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'max_answers_per_passage' + ) and self.max_answers_per_passage is not None: + _dict['max_answers_per_passage'] = self.max_answers_per_passage + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryLargePassages object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryLargePassages') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryLargePassages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryLargeSimilar(): + """ + Finds results from documents that are similar to documents of interest. Use this + parameter to add a *More like these* function to your search. You can include this + parameter with or without a **query**, **filter** or **natural_language_query** + parameter. + + :attr bool enabled: (optional) When `true`, includes documents in the query + results that are similar to documents you specify. + :attr List[str] document_ids: (optional) The list of documents of interest. + Required if **enabled** is `true`. + :attr List[str] fields: (optional) Looks for similarities in the specified + subset of fields in the documents. If not specified, all of the document fields + are used. + """ + + def __init__(self, + *, + enabled: bool = None, + document_ids: List[str] = None, + fields: List[str] = None) -> None: + """ + Initialize a QueryLargeSimilar object. + + :param bool enabled: (optional) When `true`, includes documents in the + query results that are similar to documents you specify. + :param List[str] document_ids: (optional) The list of documents of + interest. Required if **enabled** is `true`. + :param List[str] fields: (optional) Looks for similarities in the specified + subset of fields in the documents. If not specified, all of the document + fields are used. + """ + self.enabled = enabled + self.document_ids = document_ids + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryLargeSimilar': + """Initialize a QueryLargeSimilar object from a json dictionary.""" + args = {} + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'document_ids' in _dict: + args['document_ids'] = _dict.get('document_ids') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryLargePassages object from a json dictionary.""" + """Initialize a QueryLargeSimilar object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -5071,22 +8499,10 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'enabled') and self.enabled is not None: _dict['enabled'] = self.enabled - if hasattr(self, 'per_document') and self.per_document is not None: - _dict['per_document'] = self.per_document - if hasattr(self, - 'max_per_document') and self.max_per_document is not None: - _dict['max_per_document'] = self.max_per_document + if hasattr(self, 'document_ids') and self.document_ids is not None: + _dict['document_ids'] = self.document_ids if hasattr(self, 'fields') and self.fields is not None: _dict['fields'] = self.fields - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'characters') and self.characters is not None: - _dict['characters'] = self.characters - if hasattr(self, 'find_answers') and self.find_answers is not None: - _dict['find_answers'] = self.find_answers - if hasattr(self, 'max_answers_per_passage' - ) and self.max_answers_per_passage is not None: - _dict['max_answers_per_passage'] = self.max_answers_per_passage return _dict def _to_dict(self): @@ -5094,23 +8510,25 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryLargePassages object.""" + """Return a `str` version of this QueryLargeSimilar object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryLargePassages') -> bool: + def __eq__(self, other: 'QueryLargeSimilar') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryLargePassages') -> bool: + def __ne__(self, other: 'QueryLargeSimilar') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class QueryLargeSuggestedRefinements(): """ - Configuration for suggested refinements. Available with Premium plans only. + Configuration for suggested refinements. + **Note**: The **suggested_refinements** parameter that identified dynamic facets from + the data is deprecated. :attr bool enabled: (optional) Whether to perform suggested refinements. :attr int count: (optional) Maximum number of suggested refinements texts to be @@ -5263,7 +8681,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': args['matching_results'] = _dict.get('matching_results') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -5279,7 +8697,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -5301,6 +8725,66 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: return not self == other +class QueryPairAggregationResult(): + """ + Result for the `pair` aggregation. + + :attr List[dict] aggregations: (optional) Array of subaggregations of type + `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix that + is returned contains a **relevancy** value that is calculated from the + combination of each value from the first and second aggregations. + """ + + def __init__(self, *, aggregations: List[dict] = None) -> None: + """ + Initialize a QueryPairAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix + that is returned contains a **relevancy** value that is calculated from the + combination of each value from the first and second aggregations. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryPairAggregationResult': + """Initialize a QueryPairAggregationResult object from a json dictionary.""" + args = {} + if 'aggregations' in _dict: + args['aggregations'] = _dict.get('aggregations') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryPairAggregationResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryPairAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryPairAggregationResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryPairAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryResponse(): """ A response that contains the documents and aggregations for the query. @@ -5315,11 +8799,14 @@ class QueryResponse(): type information. :attr str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. - :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of - suggested refinements. + :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) + Deprecated: Array of suggested refinements. **Note**: The + `suggested_refinements` parameter that identified dynamic facets from the data + is deprecated. :attr List[QueryTableResult] table_results: (optional) Array of table results. :attr List[QueryResponsePassage] passages: (optional) Passages that best match - the query from across all of the collections in the project. + the query from across all of the collections in the project. Returned if + **passages.per_document** is `false`. """ def __init__(self, @@ -5347,11 +8834,14 @@ def __init__(self, :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. :param List[QuerySuggestedRefinement] suggested_refinements: (optional) - Array of suggested refinements. + Deprecated: Array of suggested refinements. **Note**: The + `suggested_refinements` parameter that identified dynamic facets from the + data is deprecated. :param List[QueryTableResult] table_results: (optional) Array of table results. :param List[QueryResponsePassage] passages: (optional) Passages that best - match the query from across all of the collections in the project. + match the query from across all of the collections in the project. Returned + if **passages.per_document** is `false`. """ self.matching_results = matching_results self.results = results @@ -5370,11 +8860,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryResult.from_dict(x) for x in _dict.get('results') + QueryResult.from_dict(v) for v in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] if 'retrieval_details' in _dict: args['retrieval_details'] = RetrievalDetails.from_dict( @@ -5383,17 +8873,17 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': args['suggested_query'] = _dict.get('suggested_query') if 'suggested_refinements' in _dict: args['suggested_refinements'] = [ - QuerySuggestedRefinement.from_dict(x) - for x in _dict.get('suggested_refinements') + QuerySuggestedRefinement.from_dict(v) + for v in _dict.get('suggested_refinements') ] if 'table_results' in _dict: args['table_results'] = [ - QueryTableResult.from_dict(x) - for x in _dict.get('table_results') + QueryTableResult.from_dict(v) + for v in _dict.get('table_results') ] if 'passages' in _dict: args['passages'] = [ - QueryResponsePassage.from_dict(x) for x in _dict.get('passages') + QueryResponsePassage.from_dict(v) for v in _dict.get('passages') ] return cls(**args) @@ -5409,24 +8899,55 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details.to_dict() + if isinstance(self.retrieval_details, dict): + _dict['retrieval_details'] = self.retrieval_details + else: + _dict['retrieval_details'] = self.retrieval_details.to_dict() if hasattr(self, 'suggested_query') and self.suggested_query is not None: _dict['suggested_query'] = self.suggested_query if hasattr(self, 'suggested_refinements' ) and self.suggested_refinements is not None: - _dict['suggested_refinements'] = [ - x.to_dict() for x in self.suggested_refinements - ] + suggested_refinements_list = [] + for v in self.suggested_refinements: + if isinstance(v, dict): + suggested_refinements_list.append(v) + else: + suggested_refinements_list.append(v.to_dict()) + _dict['suggested_refinements'] = suggested_refinements_list if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = [x.to_dict() for x in self.table_results] + table_results_list = [] + for v in self.table_results: + if isinstance(v, dict): + table_results_list.append(v) + else: + table_results_list.append(v.to_dict()) + _dict['table_results'] = table_results_list if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] + passages_list = [] + for v in self.passages: + if isinstance(v, dict): + passages_list.append(v) + else: + passages_list.append(v.to_dict()) + _dict['passages'] = passages_list return _dict def _to_dict(self): @@ -5454,7 +8975,9 @@ class QueryResponsePassage(): :attr str passage_text: (optional) The content of the extracted passage. :attr float passage_score: (optional) The confidence score of the passage's - analysis. A higher score indicates greater confidence. + analysis. A higher score indicates greater confidence. The score is used to rank + the passages from all documents and is returned only if + **passages.per_document** is `false`. :attr str document_id: (optional) The unique identifier of the ingested document. :attr str collection_id: (optional) The unique identifier of the collection. @@ -5464,10 +8987,9 @@ class QueryResponsePassage(): extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. - :attr float confidence: (optional) An estimate of the probability that the - passage is relevant. :attr List[ResultPassageAnswer] answers: (optional) An array of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `false`. """ def __init__(self, @@ -5479,14 +9001,15 @@ def __init__(self, start_offset: int = None, end_offset: int = None, field: str = None, - confidence: float = None, answers: List['ResultPassageAnswer'] = None) -> None: """ Initialize a QueryResponsePassage object. :param str passage_text: (optional) The content of the extracted passage. :param float passage_score: (optional) The confidence score of the - passage's analysis. A higher score indicates greater confidence. + passage's analysis. A higher score indicates greater confidence. The score + is used to rank the passages from all documents and is returned only if + **passages.per_document** is `false`. :param str document_id: (optional) The unique identifier of the ingested document. :param str collection_id: (optional) The unique identifier of the @@ -5497,10 +9020,9 @@ def __init__(self, the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. - :param float confidence: (optional) An estimate of the probability that the - passage is relevant. :param List[ResultPassageAnswer] answers: (optional) An array of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `false`. """ self.passage_text = passage_text self.passage_score = passage_score @@ -5509,7 +9031,6 @@ def __init__(self, self.start_offset = start_offset self.end_offset = end_offset self.field = field - self.confidence = confidence self.answers = answers @classmethod @@ -5530,11 +9051,9 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': args['end_offset'] = _dict.get('end_offset') if 'field' in _dict: args['field'] = _dict.get('field') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') if 'answers' in _dict: args['answers'] = [ - ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') ] return cls(**args) @@ -5560,10 +9079,14 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -5593,7 +9116,8 @@ class QueryResult(): :attr dict metadata: (optional) Metadata of the document. :attr QueryResultMetadata result_metadata: Metadata of a query result. :attr List[QueryResultPassage] document_passages: (optional) Passages from the - document that best matches the query. + document that best matches the query. Returned if **passages.per_document** is + `true`. """ # The set of defined properties for the class @@ -5614,7 +9138,8 @@ def __init__(self, :param QueryResultMetadata result_metadata: Metadata of a query result. :param dict metadata: (optional) Metadata of the document. :param List[QueryResultPassage] document_passages: (optional) Passages from - the document that best matches the query. + the document that best matches the query. Returned if + **passages.per_document** is `true`. :param **kwargs: (optional) Any additional properties. """ self.document_id = document_id @@ -5645,8 +9170,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryResult': ) if 'document_passages' in _dict: args['document_passages'] = [ - QueryResultPassage.from_dict(x) - for x in _dict.get('document_passages') + QueryResultPassage.from_dict(v) + for v in _dict.get('document_passages') ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -5666,17 +9191,23 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'document_passages') and self.document_passages is not None: - _dict['document_passages'] = [ - x.to_dict() for x in self.document_passages - ] + document_passages_list = [] + for v in self.document_passages: + if isinstance(v, dict): + document_passages_list.append(v) + else: + document_passages_list.append(v.to_dict()) + _dict['document_passages'] = document_passages_list for _key in [ k for k in vars(self).keys() if k not in QueryResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -5728,11 +9259,11 @@ class QueryResultMetadata(): :attr str collection_id: The collection id associated with this training data set. :attr float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can + Calculated based on how relevant the result is estimated to be. The score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the result set. This - field is only returned if the **natural_language_query** parameter is specified + field is returned only if the **natural_language_query** parameter is specified in the query. """ @@ -5749,11 +9280,11 @@ def __init__(self, :param str document_retrieval_source: (optional) The document retrieval source that produced this search result. :param float confidence: (optional) The confidence score for the given - result. Calculated based on how relevant the result is estimated to be. - confidence can range from `0.0` to `1.0`. The higher the number, the more + result. Calculated based on how relevant the result is estimated to be. The + score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the - result set. This field is only returned if the **natural_language_query** + result set. This field is returned only if the **natural_language_query** parameter is specified in the query. """ self.document_retrieval_source = document_retrieval_source @@ -5831,10 +9362,9 @@ class QueryResultPassage(): extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. - :attr float confidence: (optional) Estimate of the probability that the passage - is relevant. :attr List[ResultPassageAnswer] answers: (optional) An arry of extracted answers - to the specified query. + to the specified query. Returned for natural language queries when + **passages.per_document** is `true`. """ def __init__(self, @@ -5843,7 +9373,6 @@ def __init__(self, start_offset: int = None, end_offset: int = None, field: str = None, - confidence: float = None, answers: List['ResultPassageAnswer'] = None) -> None: """ Initialize a QueryResultPassage object. @@ -5855,16 +9384,14 @@ def __init__(self, the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. - :param float confidence: (optional) Estimate of the probability that the - passage is relevant. :param List[ResultPassageAnswer] answers: (optional) An arry of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `true`. """ self.passage_text = passage_text self.start_offset = start_offset self.end_offset = end_offset self.field = field - self.confidence = confidence self.answers = answers @classmethod @@ -5879,11 +9406,9 @@ def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': args['end_offset'] = _dict.get('end_offset') if 'field' in _dict: args['field'] = _dict.get('field') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') if 'answers' in _dict: args['answers'] = [ - ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') ] return cls(**args) @@ -5903,10 +9428,14 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -5930,7 +9459,8 @@ def __ne__(self, other: 'QueryResultPassage') -> bool: class QuerySuggestedRefinement(): """ - A suggested additional query term or terms user to filter results. + A suggested additional query term or terms user to filter results. **Note**: The + `suggested_refinements` parameter is deprecated. :attr str text: (optional) The text used to filter. """ @@ -6067,7 +9597,10 @@ def to_dict(self) -> Dict: 'table_html_offset') and self.table_html_offset is not None: _dict['table_html_offset'] = self.table_html_offset if hasattr(self, 'table') and self.table is not None: - _dict['table'] = self.table.to_dict() + if isinstance(self.table, dict): + _dict['table'] = self.table + else: + _dict['table'] = self.table.to_dict() return _dict def _to_dict(self): @@ -6091,19 +9624,21 @@ def __ne__(self, other: 'QueryTableResult') -> bool: class QueryTermAggregationResult(): """ - Top value result for the term aggregation. + Top value result for the `term` aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. + :attr str key: Value of the field with a nonzero frequency in the document set. :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this term. - :attr int total_matching_documents: (optional) The number of documents which - have the term as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr float relevancy: (optional) The relevancy score for this result. Returned + only if `relevancy:true` is specified in the request. + :attr int total_matching_documents: (optional) Number of documents in the + collection that contain the term in the specified field. Returned only when + `relevancy:true` is specified in the request. + :attr float estimated_matching_results: (optional) Number of documents that are + estimated to match the query and also meet the condition. Returned only when + `relevancy:true` is specified in the request. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is combined with other aggregations in the request or + is returned as a subaggregation. """ def __init__(self, @@ -6112,30 +9647,31 @@ def __init__(self, *, relevancy: float = None, total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + estimated_matching_results: float = None, + aggregations: List[dict] = None) -> None: """ Initialize a QueryTermAggregationResult object. - :param str key: Value of the field with a non-zero frequency in the - document set. + :param str key: Value of the field with a nonzero frequency in the document + set. :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents - which have the term as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param float relevancy: (optional) The relevancy score for this result. + Returned only if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents in the + collection that contain the term in the specified field. Returned only when + `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) Number of documents + that are estimated to match the query and also meet the condition. Returned + only when `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is combined with other aggregations in + the request or is returned as a subaggregation. """ self.key = key self.matching_results = matching_results self.relevancy = relevancy self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents + self.estimated_matching_results = estimated_matching_results self.aggregations = aggregations @classmethod @@ -6159,13 +9695,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': if 'total_matching_documents' in _dict: args['total_matching_documents'] = _dict.get( 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') + if 'estimated_matching_results' in _dict: + args['estimated_matching_results'] = _dict.get( + 'estimated_matching_results') if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -6186,12 +9720,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'total_matching_documents' ) and self.total_matching_documents is not None: _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: + if hasattr(self, 'estimated_matching_results' + ) and self.estimated_matching_results is not None: _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents + 'estimated_matching_results'] = self.estimated_matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -6223,8 +9757,8 @@ class QueryTimesliceAggregationResult(): in UNIX milliseconds since epoch. :attr int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ def __init__(self, @@ -6232,7 +9766,7 @@ def __init__(self, key: int, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + aggregations: List[dict] = None) -> None: """ Initialize a QueryTimesliceAggregationResult object. @@ -6242,8 +9776,8 @@ def __init__(self, interval in UNIX milliseconds since epoch. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key_as_string = key_as_string self.key = key @@ -6273,9 +9807,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -6294,7 +9826,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -6321,7 +9853,8 @@ class QueryTopHitsAggregationResult(): A query response that contains the matching documents for the preceding aggregations. :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results. + :attr List[dict] hits: (optional) An array of the document results in an ordered + list. """ def __init__(self, @@ -6332,7 +9865,8 @@ def __init__(self, Initialize a QueryTopHitsAggregationResult object. :param int matching_results: Number of matching results. - :param List[dict] hits: (optional) An array of the document results. + :param List[dict] hits: (optional) An array of the document results in an + ordered list. """ self.matching_results = matching_results self.hits = hits @@ -6385,6 +9919,126 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: return not self == other +class QueryTopicAggregationResult(): + """ + Result for the `topic` aggregation. + + :attr List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **topic_indicator** that is calculated from the combination + of each aggregation value and segment of time. + """ + + def __init__(self, *, aggregations: List[dict] = None) -> None: + """ + Initialize a QueryTopicAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of + type `term` or `group_by` and `timeslice`. Each element of the matrix that + is returned contains a **topic_indicator** that is calculated from the + combination of each aggregation value and segment of time. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTopicAggregationResult': + """Initialize a QueryTopicAggregationResult object from a json dictionary.""" + args = {} + if 'aggregations' in _dict: + args['aggregations'] = _dict.get('aggregations') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopicAggregationResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryTopicAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTopicAggregationResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryTopicAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTrendAggregationResult(): + """ + Result for the `trend` aggregation. + + :attr List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **trend_indicator** that is calculated from the combination + of each aggregation value and segment of time. + """ + + def __init__(self, *, aggregations: List[dict] = None) -> None: + """ + Initialize a QueryTrendAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **trend_indicator** that is calculated from the + combination of each aggregation value and segment of time. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTrendAggregationResult': + """Initialize a QueryTrendAggregationResult object from a json dictionary.""" + args = {} + if 'aggregations' in _dict: + args['aggregations'] = _dict.get('aggregations') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTrendAggregationResult object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryTrendAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTrendAggregationResult') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryTrendAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResultPassageAnswer(): """ Object that contains a potential answer to the specified query. @@ -6552,6 +10206,64 @@ class DocumentRetrievalStrategyEnum(str, Enum): RELEVANCY_TRAINING = 'relevancy_training' +class StopWordList(): + """ + List of words to filter out of text that is submitted in queries. + + :attr List[str] stopwords: List of stop words. + """ + + def __init__(self, stopwords: List[str]) -> None: + """ + Initialize a StopWordList object. + + :param List[str] stopwords: List of stop words. + """ + self.stopwords = stopwords + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StopWordList': + """Initialize a StopWordList object from a json dictionary.""" + args = {} + if 'stopwords' in _dict: + args['stopwords'] = _dict.get('stopwords') + else: + raise ValueError( + 'Required property \'stopwords\' not present in StopWordList JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StopWordList object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'stopwords') and self.stopwords is not None: + _dict['stopwords'] = self.stopwords + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this StopWordList object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StopWordList') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'StopWordList') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TableBodyCells(): """ Cells that are not table header, column header, or row header cells. @@ -6674,37 +10386,37 @@ def from_dict(cls, _dict: Dict) -> 'TableBodyCells': args['column_index_end'] = _dict.get('column_index_end') if 'row_header_ids' in _dict: args['row_header_ids'] = [ - TableRowHeaderIds.from_dict(x) - for x in _dict.get('row_header_ids') + TableRowHeaderIds.from_dict(v) + for v in _dict.get('row_header_ids') ] if 'row_header_texts' in _dict: args['row_header_texts'] = [ - TableRowHeaderTexts.from_dict(x) - for x in _dict.get('row_header_texts') + TableRowHeaderTexts.from_dict(v) + for v in _dict.get('row_header_texts') ] if 'row_header_texts_normalized' in _dict: args['row_header_texts_normalized'] = [ - TableRowHeaderTextsNormalized.from_dict(x) - for x in _dict.get('row_header_texts_normalized') + TableRowHeaderTextsNormalized.from_dict(v) + for v in _dict.get('row_header_texts_normalized') ] if 'column_header_ids' in _dict: args['column_header_ids'] = [ - TableColumnHeaderIds.from_dict(x) - for x in _dict.get('column_header_ids') + TableColumnHeaderIds.from_dict(v) + for v in _dict.get('column_header_ids') ] if 'column_header_texts' in _dict: args['column_header_texts'] = [ - TableColumnHeaderTexts.from_dict(x) - for x in _dict.get('column_header_texts') + TableColumnHeaderTexts.from_dict(v) + for v in _dict.get('column_header_texts') ] if 'column_header_texts_normalized' in _dict: args['column_header_texts_normalized'] = [ - TableColumnHeaderTextsNormalized.from_dict(x) - for x in _dict.get('column_header_texts_normalized') + TableColumnHeaderTextsNormalized.from_dict(v) + for v in _dict.get('column_header_texts_normalized') ] if 'attributes' in _dict: args['attributes'] = [ - DocumentAttribute.from_dict(x) for x in _dict.get('attributes') + DocumentAttribute.from_dict(v) for v in _dict.get('attributes') ] return cls(**args) @@ -6719,7 +10431,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -6735,35 +10450,69 @@ def to_dict(self) -> Dict: 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: - _dict['row_header_ids'] = [x.to_dict() for x in self.row_header_ids] + row_header_ids_list = [] + for v in self.row_header_ids: + if isinstance(v, dict): + row_header_ids_list.append(v) + else: + row_header_ids_list.append(v.to_dict()) + _dict['row_header_ids'] = row_header_ids_list if hasattr(self, 'row_header_texts') and self.row_header_texts is not None: - _dict['row_header_texts'] = [ - x.to_dict() for x in self.row_header_texts - ] + row_header_texts_list = [] + for v in self.row_header_texts: + if isinstance(v, dict): + row_header_texts_list.append(v) + else: + row_header_texts_list.append(v.to_dict()) + _dict['row_header_texts'] = row_header_texts_list if hasattr(self, 'row_header_texts_normalized' ) and self.row_header_texts_normalized is not None: - _dict['row_header_texts_normalized'] = [ - x.to_dict() for x in self.row_header_texts_normalized - ] + row_header_texts_normalized_list = [] + for v in self.row_header_texts_normalized: + if isinstance(v, dict): + row_header_texts_normalized_list.append(v) + else: + row_header_texts_normalized_list.append(v.to_dict()) + _dict[ + 'row_header_texts_normalized'] = row_header_texts_normalized_list if hasattr(self, 'column_header_ids') and self.column_header_ids is not None: - _dict['column_header_ids'] = [ - x.to_dict() for x in self.column_header_ids - ] + column_header_ids_list = [] + for v in self.column_header_ids: + if isinstance(v, dict): + column_header_ids_list.append(v) + else: + column_header_ids_list.append(v.to_dict()) + _dict['column_header_ids'] = column_header_ids_list if hasattr( self, 'column_header_texts') and self.column_header_texts is not None: - _dict['column_header_texts'] = [ - x.to_dict() for x in self.column_header_texts - ] + column_header_texts_list = [] + for v in self.column_header_texts: + if isinstance(v, dict): + column_header_texts_list.append(v) + else: + column_header_texts_list.append(v.to_dict()) + _dict['column_header_texts'] = column_header_texts_list if hasattr(self, 'column_header_texts_normalized' ) and self.column_header_texts_normalized is not None: - _dict['column_header_texts_normalized'] = [ - x.to_dict() for x in self.column_header_texts_normalized - ] + column_header_texts_normalized_list = [] + for v in self.column_header_texts_normalized: + if isinstance(v, dict): + column_header_texts_normalized_list.append(v) + else: + column_header_texts_normalized_list.append(v.to_dict()) + _dict[ + 'column_header_texts_normalized'] = column_header_texts_normalized_list if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x.to_dict() for x in self.attributes] + attributes_list = [] + for v in self.attributes: + if isinstance(v, dict): + attributes_list.append(v) + else: + attributes_list.append(v.to_dict()) + _dict['attributes'] = attributes_list return _dict def _to_dict(self): @@ -6840,7 +10589,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -6919,7 +10671,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -7117,7 +10872,7 @@ class TableColumnHeaders(): itself, of the current table. :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the column header cell in the + :attr dict location: (optional) The location of the column header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :attr str text: (optional) The textual contents of this cell from the input @@ -7138,7 +10893,7 @@ class TableColumnHeaders(): def __init__(self, *, cell_id: str = None, - location: object = None, + location: dict = None, text: str = None, text_normalized: str = None, row_index_begin: int = None, @@ -7150,8 +10905,8 @@ def __init__(self, :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the column header cell - in the current table as defined by its `begin` and `end` offsets, + :param dict location: (optional) The location of the column header cell in + the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. @@ -7323,7 +11078,7 @@ class TableHeaders(): The contents of the current table's header. :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the table header cell in the + :attr dict location: (optional) The location of the table header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :attr str text: (optional) The textual contents of the cell from the input @@ -7341,7 +11096,7 @@ class TableHeaders(): def __init__(self, *, cell_id: str = None, - location: object = None, + location: dict = None, text: str = None, row_index_begin: int = None, row_index_end: int = None, @@ -7352,7 +11107,7 @@ def __init__(self, :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the table header cell in + :param dict location: (optional) The location of the table header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :param str text: (optional) The textual contents of the cell from the input @@ -7472,7 +11227,7 @@ def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': args['key'] = TableCellKey.from_dict(_dict.get('key')) if 'value' in _dict: args['value'] = [ - TableCellValues.from_dict(x) for x in _dict.get('value') + TableCellValues.from_dict(v) for v in _dict.get('value') ] return cls(**args) @@ -7485,9 +11240,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key.to_dict() + if isinstance(self.key, dict): + _dict['key'] = self.key + else: + _dict['key'] = self.key.to_dict() if hasattr(self, 'value') and self.value is not None: - _dict['value'] = [x.to_dict() for x in self.value] + value_list = [] + for v in self.value: + if isinstance(v, dict): + value_list.append(v) + else: + value_list.append(v.to_dict()) + _dict['value'] = value_list return _dict def _to_dict(self): @@ -7607,29 +11371,29 @@ def from_dict(cls, _dict: Dict) -> 'TableResultTable': args['title'] = TableTextLocation.from_dict(_dict.get('title')) if 'table_headers' in _dict: args['table_headers'] = [ - TableHeaders.from_dict(x) for x in _dict.get('table_headers') + TableHeaders.from_dict(v) for v in _dict.get('table_headers') ] if 'row_headers' in _dict: args['row_headers'] = [ - TableRowHeaders.from_dict(x) for x in _dict.get('row_headers') + TableRowHeaders.from_dict(v) for v in _dict.get('row_headers') ] if 'column_headers' in _dict: args['column_headers'] = [ - TableColumnHeaders.from_dict(x) - for x in _dict.get('column_headers') + TableColumnHeaders.from_dict(v) + for v in _dict.get('column_headers') ] if 'key_value_pairs' in _dict: args['key_value_pairs'] = [ - TableKeyValuePairs.from_dict(x) - for x in _dict.get('key_value_pairs') + TableKeyValuePairs.from_dict(v) + for v in _dict.get('key_value_pairs') ] if 'body_cells' in _dict: args['body_cells'] = [ - TableBodyCells.from_dict(x) for x in _dict.get('body_cells') + TableBodyCells.from_dict(v) for v in _dict.get('body_cells') ] if 'contexts' in _dict: args['contexts'] = [ - TableTextLocation.from_dict(x) for x in _dict.get('contexts') + TableTextLocation.from_dict(v) for v in _dict.get('contexts') ] return cls(**args) @@ -7642,28 +11406,71 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'section_title') and self.section_title is not None: - _dict['section_title'] = self.section_title.to_dict() + if isinstance(self.section_title, dict): + _dict['section_title'] = self.section_title + else: + _dict['section_title'] = self.section_title.to_dict() if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() + if isinstance(self.title, dict): + _dict['title'] = self.title + else: + _dict['title'] = self.title.to_dict() if hasattr(self, 'table_headers') and self.table_headers is not None: - _dict['table_headers'] = [x.to_dict() for x in self.table_headers] + table_headers_list = [] + for v in self.table_headers: + if isinstance(v, dict): + table_headers_list.append(v) + else: + table_headers_list.append(v.to_dict()) + _dict['table_headers'] = table_headers_list if hasattr(self, 'row_headers') and self.row_headers is not None: - _dict['row_headers'] = [x.to_dict() for x in self.row_headers] + row_headers_list = [] + for v in self.row_headers: + if isinstance(v, dict): + row_headers_list.append(v) + else: + row_headers_list.append(v.to_dict()) + _dict['row_headers'] = row_headers_list if hasattr(self, 'column_headers') and self.column_headers is not None: - _dict['column_headers'] = [x.to_dict() for x in self.column_headers] + column_headers_list = [] + for v in self.column_headers: + if isinstance(v, dict): + column_headers_list.append(v) + else: + column_headers_list.append(v.to_dict()) + _dict['column_headers'] = column_headers_list if hasattr(self, 'key_value_pairs') and self.key_value_pairs is not None: - _dict['key_value_pairs'] = [ - x.to_dict() for x in self.key_value_pairs - ] + key_value_pairs_list = [] + for v in self.key_value_pairs: + if isinstance(v, dict): + key_value_pairs_list.append(v) + else: + key_value_pairs_list.append(v.to_dict()) + _dict['key_value_pairs'] = key_value_pairs_list if hasattr(self, 'body_cells') and self.body_cells is not None: - _dict['body_cells'] = [x.to_dict() for x in self.body_cells] + body_cells_list = [] + for v in self.body_cells: + if isinstance(v, dict): + body_cells_list.append(v) + else: + body_cells_list.append(v.to_dict()) + _dict['body_cells'] = body_cells_list if hasattr(self, 'contexts') and self.contexts is not None: - _dict['contexts'] = [x.to_dict() for x in self.contexts] + contexts_list = [] + for v in self.contexts: + if isinstance(v, dict): + contexts_list.append(v) + else: + contexts_list.append(v.to_dict()) + _dict['contexts'] = contexts_list return _dict def _to_dict(self): @@ -7952,7 +11759,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -8038,7 +11848,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -8166,7 +11979,8 @@ class TrainingQuery(): Object that contains training query details. :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: The natural text query for the training query. + :attr str natural_language_query: The natural text query that is used as the + training query. :attr str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. :attr datetime created: (optional) The date and time the query was created. @@ -8185,8 +11999,8 @@ def __init__(self, """ Initialize a TrainingQuery object. - :param str natural_language_query: The natural text query for the training - query. + :param str natural_language_query: The natural text query that is used as + the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. @@ -8218,7 +12032,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingQuery': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') + TrainingExample.from_dict(v) for v in _dict.get('examples') ] else: raise ValueError( @@ -8246,7 +12060,79 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TrainingQuery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TrainingQuery') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TrainingQuery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TrainingQuerySet(): + """ + Object specifying the training queries contained in the identified training set. + + :attr List[TrainingQuery] queries: (optional) Array of training queries. At + least 50 queries are required for training to begin. A maximum of 10,000 queries + are returned. + """ + + def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: + """ + Initialize a TrainingQuerySet object. + + :param List[TrainingQuery] queries: (optional) Array of training queries. + At least 50 queries are required for training to begin. A maximum of 10,000 + queries are returned. + """ + self.queries = queries + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': + """Initialize a TrainingQuerySet object from a json dictionary.""" + args = {} + if 'queries' in _dict: + args['queries'] = [ + TrainingQuery.from_dict(v) for v in _dict.get('queries') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuerySet object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'queries') and self.queries is not None: + queries_list = [] + for v in self.queries: + if isinstance(v, dict): + queries_list.append(v) + else: + queries_list.append(v.to_dict()) + _dict['queries'] = queries_list return _dict def _to_dict(self): @@ -8254,55 +12140,61 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TrainingQuery object.""" + """Return a `str` version of this TrainingQuerySet object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TrainingQuery') -> bool: + def __eq__(self, other: 'TrainingQuerySet') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TrainingQuery') -> bool: + def __ne__(self, other: 'TrainingQuerySet') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TrainingQuerySet(): +class UpdateDocumentClassifier(): """ - Object specifying the training queries contained in the identified training set. + An object that contains a new name or description for a document classifier, updated + training data, or new or updated test data. - :attr List[TrainingQuery] queries: (optional) Array of training queries. + :attr str name: (optional) A new name for the classifier. + :attr str description: (optional) A new description for the classifier. """ - def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: + def __init__(self, *, name: str = None, description: str = None) -> None: """ - Initialize a TrainingQuerySet object. + Initialize a UpdateDocumentClassifier object. - :param List[TrainingQuery] queries: (optional) Array of training queries. + :param str name: (optional) A new name for the classifier. + :param str description: (optional) A new description for the classifier. """ - self.queries = queries + self.name = name + self.description = description @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': - """Initialize a TrainingQuerySet object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'UpdateDocumentClassifier': + """Initialize a UpdateDocumentClassifier object from a json dictionary.""" args = {} - if 'queries' in _dict: - args['queries'] = [ - TrainingQuery.from_dict(x) for x in _dict.get('queries') - ] + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TrainingQuerySet object from a json dictionary.""" + """Initialize a UpdateDocumentClassifier object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x.to_dict() for x in self.queries] + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description return _dict def _to_dict(self): @@ -8310,58 +12202,61 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TrainingQuerySet object.""" + """Return a `str` version of this UpdateDocumentClassifier object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TrainingQuerySet') -> bool: + def __eq__(self, other: 'UpdateDocumentClassifier') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TrainingQuerySet') -> bool: + def __ne__(self, other: 'UpdateDocumentClassifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryCalculationAggregation(QueryAggregation): +class QueryAggregationQueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible calculations include min, max, sum, average, and unique_count. + :attr str type: (optional) Specifies the calculation type, such as 'average`, + `max`, `min`, `sum`, or `unique_count`. :attr str field: The field to perform the calculation on. :attr float value: (optional) The value of the calculation. """ - def __init__(self, type: str, field: str, *, value: float = None) -> None: + def __init__(self, + field: str, + *, + type: str = None, + value: float = None) -> None: """ - Initialize a QueryCalculationAggregation object. + Initialize a QueryAggregationQueryCalculationAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str field: The field to perform the calculation on. + :param str type: (optional) Specifies the calculation type, such as + 'average`, `max`, `min`, `sum`, or `unique_count`. :param float value: (optional) The value of the calculation. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryCalculationAggregation': + """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryCalculationAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') else: raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryCalculationAggregation JSON' ) if 'value' in _dict: args['value'] = _dict.get('value') @@ -8369,7 +12264,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8388,85 +12283,80 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryCalculationAggregation object.""" + """Return a `str` version of this QueryAggregationQueryCalculationAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryCalculationAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryCalculationAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryCalculationAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryCalculationAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryFilterAggregation(QueryAggregation): +class QueryAggregationQueryFilterAggregation(QueryAggregation): """ - A modifier that narrows the document set of the sub-aggregations it precedes. + A modifier that narrows the document set of the subaggregations it precedes. + :attr str type: (optional) Specifies that the aggregation type is `filter`. :attr str match: The filter that is written in Discovery Query Language syntax - and is applied to the documents before sub-aggregations are run. + and is applied to the documents before subaggregations are run. :attr int matching_results: Number of documents that match the filter. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. """ def __init__(self, - type: str, match: str, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + type: str = None, + aggregations: List[dict] = None) -> None: """ - Initialize a QueryFilterAggregation object. + Initialize a QueryAggregationQueryFilterAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str match: The filter that is written in Discovery Query Language - syntax and is applied to the documents before sub-aggregations are run. + syntax and is applied to the documents before subaggregations are run. :param int matching_results: Number of documents that match the filter. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str type: (optional) Specifies that the aggregation type is + `filter`. + :param List[dict] aggregations: (optional) An array of subaggregations. """ + # pylint: disable=super-init-not-called self.type = type self.match = match self.matching_results = matching_results self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': - """Initialize a QueryFilterAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryFilterAggregation': + """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryFilterAggregation JSON' - ) if 'match' in _dict: args['match'] = _dict.get('match') else: raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' + 'Required property \'match\' not present in QueryAggregationQueryFilterAggregation JSON' ) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') else: raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' + 'Required property \'matching_results\' not present in QueryAggregationQueryFilterAggregation JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryFilterAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8480,7 +12370,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -8488,64 +12378,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryFilterAggregation object.""" + """Return a `str` version of this QueryAggregationQueryFilterAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryFilterAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryFilterAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryFilterAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryFilterAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryGroupByAggregation(QueryAggregation): +class QueryAggregationQueryGroupByAggregation(QueryAggregation): """ - Returns the top values for the field specified. + Separates document results into groups that meet the conditions you specify. - :attr List[QueryGroupByAggregationResult] results: (optional) Array of top - values for the field. + :attr str type: (optional) Specifies that the aggregation type is `group_by`. + :attr List[QueryGroupByAggregationResult] results: (optional) An array of + results. """ def __init__(self, - type: str, *, + type: str = None, results: List['QueryGroupByAggregationResult'] = None) -> None: """ - Initialize a QueryGroupByAggregation object. + Initialize a QueryAggregationQueryGroupByAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param List[QueryGroupByAggregationResult] results: (optional) Array of top - values for the field. + :param str type: (optional) Specifies that the aggregation type is + `group_by`. + :param List[QueryGroupByAggregationResult] results: (optional) An array of + results. """ + # pylint: disable=super-init-not-called self.type = type self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': - """Initialize a QueryGroupByAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryGroupByAggregation': + """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryGroupByAggregation JSON' - ) if 'results' in _dict: args['results'] = [ - QueryGroupByAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryGroupByAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryGroupByAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8554,7 +12442,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8562,55 +12456,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryGroupByAggregation object.""" + """Return a `str` version of this QueryAggregationQueryGroupByAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryGroupByAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryGroupByAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryGroupByAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryGroupByAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryHistogramAggregation(QueryAggregation): +class QueryAggregationQueryHistogramAggregation(QueryAggregation): """ Numeric interval segments to categorize documents by using field values from a single numeric field to describe the category. + :attr str type: (optional) Specifies that the aggregation type is `histogram`. :attr str field: The numeric field name used to create the histogram. :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. + :attr str name: (optional) Identifier that can optionally be specified in the + query request of this aggregation. :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric intervals. """ def __init__( self, - type: str, field: str, interval: int, *, + type: str = None, name: str = None, results: List['QueryHistogramAggregationResult'] = None) -> None: """ - Initialize a QueryHistogramAggregation object. + Initialize a QueryAggregationQueryHistogramAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str field: The numeric field name used to create the histogram. :param int interval: The size of the sections that the results are split into. - :param str name: (optional) Identifier specified in the query request of - this aggregation. + :param str type: (optional) Specifies that the aggregation type is + `histogram`. + :param str name: (optional) Identifier that can optionally be specified in + the query request of this aggregation. :param List[QueryHistogramAggregationResult] results: (optional) Array of numeric intervals. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.interval = interval @@ -8618,39 +12513,36 @@ def __init__( self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': - """Initialize a QueryHistogramAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryHistogramAggregation': + """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryHistogramAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') else: raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryHistogramAggregation JSON' ) if 'interval' in _dict: args['interval'] = _dict.get('interval') else: raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' + 'Required property \'interval\' not present in QueryAggregationQueryHistogramAggregation JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryHistogramAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8665,7 +12557,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8673,87 +12571,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryHistogramAggregation object.""" + """Return a `str` version of this QueryAggregationQueryHistogramAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryHistogramAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryHistogramAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryHistogramAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryHistogramAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryNestedAggregation(QueryAggregation): +class QueryAggregationQueryNestedAggregation(QueryAggregation): """ - A restriction that alters the document set that is used for sub-aggregations it - precedes to nested documents found in the field specified. + A restriction that alters the document set that is used by the aggregations that it + precedes. Subsequent aggregations are applied to nested documents from the specified + field. - :attr str path: The path to the document field to scope sub-aggregations to. + :attr str type: (optional) Specifies that the aggregation type is `nested`. + :attr str path: The path to the document field to scope subsequent aggregations + to. :attr int matching_results: Number of nested documents found in the specified field. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. """ def __init__(self, - type: str, path: str, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + type: str = None, + aggregations: List[dict] = None) -> None: """ - Initialize a QueryNestedAggregation object. + Initialize a QueryAggregationQueryNestedAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str path: The path to the document field to scope sub-aggregations - to. + :param str path: The path to the document field to scope subsequent + aggregations to. :param int matching_results: Number of nested documents found in the specified field. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str type: (optional) Specifies that the aggregation type is + `nested`. + :param List[dict] aggregations: (optional) An array of subaggregations. """ + # pylint: disable=super-init-not-called self.type = type self.path = path self.matching_results = matching_results self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': - """Initialize a QueryNestedAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryNestedAggregation': + """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryNestedAggregation JSON' - ) if 'path' in _dict: args['path'] = _dict.get('path') else: raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' + 'Required property \'path\' not present in QueryAggregationQueryNestedAggregation JSON' ) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') else: raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' + 'Required property \'matching_results\' not present in QueryAggregationQueryNestedAggregation JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryNestedAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8767,7 +12662,134 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + _dict['aggregations'] = self.aggregations + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryAggregationQueryNestedAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryNestedAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryAggregationQueryNestedAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryPairAggregation(QueryAggregation): + """ + Calculates relevancy values using combinations of document sets from results of the + specified pair of aggregations. + + :attr str type: (optional) Specifies that the aggregation type is `pair`. + :attr str first: (optional) Specifies the first aggregation in the pair. The + aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :attr str second: (optional) Specifies the second aggregation in the pair. The + aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :attr bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :attr bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :attr List[QueryPairAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__(self, + *, + type: str = None, + first: str = None, + second: str = None, + show_estimated_matching_results: bool = None, + show_total_matching_documents: bool = None, + results: List['QueryPairAggregationResult'] = None) -> None: + """ + Initialize a QueryAggregationQueryPairAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `pair`. + :param str first: (optional) Specifies the first aggregation in the pair. + The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param str second: (optional) Specifies the second aggregation in the pair. + The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryPairAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.first = first + self.second = second + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryPairAggregation': + """Initialize a QueryAggregationQueryPairAggregation object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'first' in _dict: + args['first'] = _dict.get('first') + if 'second' in _dict: + args['second'] = _dict.get('second') + if 'show_estimated_matching_results' in _dict: + args['show_estimated_matching_results'] = _dict.get( + 'show_estimated_matching_results') + if 'show_total_matching_documents' in _dict: + args['show_total_matching_documents'] = _dict.get( + 'show_total_matching_documents') + if 'results' in _dict: + args['results'] = [ + QueryPairAggregationResult.from_dict(v) + for v in _dict.get('results') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryPairAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'first') and self.first is not None: + _dict['first'] = self.first + if hasattr(self, 'second') and self.second is not None: + _dict['second'] = self.second + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8775,53 +12797,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryNestedAggregation object.""" + """Return a `str` version of this QueryAggregationQueryPairAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryNestedAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryPairAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryNestedAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryPairAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTermAggregation(QueryAggregation): +class QueryAggregationQueryTermAggregation(QueryAggregation): """ - Returns the top values for the field specified. + Returns results from the field that is specified. - :attr str field: The field in the document used to generate top values from. - :attr int count: (optional) The number of top values returned. + :attr str type: (optional) Specifies that the aggregation type is `term`. + :attr str field: (optional) The field in the document where the values come + from. + :attr int count: (optional) The number of results returned. Not returned if + `relevancy:true` is specified in the request. :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryTermAggregationResult] results: (optional) Array of top values - for the field. + aggregation. Not returned if `relevancy:true` is specified in the request. + :attr List[QueryTermAggregationResult] results: (optional) An array of results. """ def __init__(self, - type: str, - field: str, *, + type: str = None, + field: str = None, count: int = None, name: str = None, results: List['QueryTermAggregationResult'] = None) -> None: """ - Initialize a QueryTermAggregation object. + Initialize a QueryAggregationQueryTermAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The field in the document used to generate top values - from. - :param int count: (optional) The number of top values returned. + :param str type: (optional) Specifies that the aggregation type is `term`. + :param str field: (optional) The field in the document where the values + come from. + :param int count: (optional) The number of results returned. Not returned + if `relevancy:true` is specified in the request. :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top - values for the field. + this aggregation. Not returned if `relevancy:true` is specified in the + request. + :param List[QueryTermAggregationResult] results: (optional) An array of + results. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.count = count @@ -8829,35 +12854,27 @@ def __init__(self, self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': - """Initialize a QueryTermAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTermAggregation': + """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTermAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) if 'count' in _dict: args['count'] = _dict.get('count') if 'name' in _dict: args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTermAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTermAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTermAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8872,7 +12889,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8880,55 +12903,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTermAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTermAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTermAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryTermAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTermAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryTermAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTimesliceAggregation(QueryAggregation): +class QueryAggregationQueryTimesliceAggregation(QueryAggregation): """ A specialized histogram aggregation that uses dates to create interval segments. + :attr str type: (optional) Specifies that the aggregation type is `timeslice`. :attr str field: The date field name used to create the timeslice. :attr str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. + :attr str name: (optional) Identifier that can optionally be specified in the + query request of this aggregation. :attr List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ def __init__( self, - type: str, field: str, interval: str, *, + type: str = None, name: str = None, results: List['QueryTimesliceAggregationResult'] = None) -> None: """ - Initialize a QueryTimesliceAggregation object. + Initialize a QueryAggregationQueryTimesliceAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str field: The date field name used to create the timeslice. :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :param str name: (optional) Identifier specified in the query request of - this aggregation. + :param str type: (optional) Specifies that the aggregation type is + `timeslice`. + :param str name: (optional) Identifier that can optionally be specified in + the query request of this aggregation. :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.interval = interval @@ -8936,39 +12960,36 @@ def __init__( self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryTimesliceAggregation': + """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTimesliceAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') else: raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) if 'interval' in _dict: args['interval'] = _dict.get('interval') else: raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' + 'Required property \'interval\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -8983,7 +13004,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8991,67 +13018,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTimesliceAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTimesliceAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTimesliceAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryTimesliceAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTimesliceAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryTimesliceAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTopHitsAggregation(QueryAggregation): +class QueryAggregationQueryTopHitsAggregation(QueryAggregation): """ Returns the top documents ranked by the score of the query. + :attr str type: (optional) Specifies that the aggregation type is `top_hits`. :attr int size: The number of documents to return. :attr str name: (optional) Identifier specified in the query request of this aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) + :attr QueryTopHitsAggregationResult hits: (optional) A query response that + contains the matching documents for the preceding aggregations. """ def __init__(self, - type: str, size: int, *, + type: str = None, name: str = None, hits: 'QueryTopHitsAggregationResult' = None) -> None: """ - Initialize a QueryTopHitsAggregation object. + Initialize a QueryAggregationQueryTopHitsAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param int size: The number of documents to return. + :param str type: (optional) Specifies that the aggregation type is + `top_hits`. :param str name: (optional) Identifier specified in the query request of this aggregation. - :param QueryTopHitsAggregationResult hits: (optional) + :param QueryTopHitsAggregationResult hits: (optional) A query response that + contains the matching documents for the preceding aggregations. """ + # pylint: disable=super-init-not-called self.type = type self.size = size self.name = name self.hits = hits @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryTopHitsAggregation': + """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTopHitsAggregation JSON' - ) if 'size' in _dict: args['size'] = _dict.get('size') else: raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' + 'Required property \'size\' not present in QueryAggregationQueryTopHitsAggregation JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') @@ -9062,7 +13091,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -9075,7 +13104,258 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits.to_dict() + if isinstance(self.hits, dict): + _dict['hits'] = self.hits + else: + _dict['hits'] = self.hits.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryAggregationQueryTopHitsAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryTopHitsAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryAggregationQueryTopHitsAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryTopicAggregation(QueryAggregation): + """ + Detects how much the frequency of a given facet value deviates from the expected + average for the given time period. This aggregation type does not use data from + previous time periods. It calculates an index by using the averages of frequency + counts of other facet values for the given time period. + + :attr str type: (optional) Specifies that the aggregation type is `topic`. + :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + the facet that you want to analyze. + :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + defines the time segments. + :attr bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :attr bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :attr List[QueryTopicAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__(self, + *, + type: str = None, + facet: str = None, + time_segments: str = None, + show_estimated_matching_results: bool = None, + show_total_matching_documents: bool = None, + results: List['QueryTopicAggregationResult'] = None) -> None: + """ + Initialize a QueryAggregationQueryTopicAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `topic`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation + for the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation + that defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTopicAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.facet = facet + self.time_segments = time_segments + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTopicAggregation': + """Initialize a QueryAggregationQueryTopicAggregation object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'facet' in _dict: + args['facet'] = _dict.get('facet') + if 'time_segments' in _dict: + args['time_segments'] = _dict.get('time_segments') + if 'show_estimated_matching_results' in _dict: + args['show_estimated_matching_results'] = _dict.get( + 'show_estimated_matching_results') + if 'show_total_matching_documents' in _dict: + args['show_total_matching_documents'] = _dict.get( + 'show_total_matching_documents') + if 'results' in _dict: + args['results'] = [ + QueryTopicAggregationResult.from_dict(v) + for v in _dict.get('results') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryTopicAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'facet') and self.facet is not None: + _dict['facet'] = self.facet + if hasattr(self, 'time_segments') and self.time_segments is not None: + _dict['time_segments'] = self.time_segments + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this QueryAggregationQueryTopicAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryTopicAggregation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'QueryAggregationQueryTopicAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryTrendAggregation(QueryAggregation): + """ + Detects sharp and unexpected changes in the frequency of a facet or facet value over + time based on the past history of frequency changes of the facet value. + + :attr str type: (optional) Specifies that the aggregation type is `trend`. + :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + the facet that you want to analyze. + :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + defines the time segments. + :attr bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :attr bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :attr List[QueryTrendAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__(self, + *, + type: str = None, + facet: str = None, + time_segments: str = None, + show_estimated_matching_results: bool = None, + show_total_matching_documents: bool = None, + results: List['QueryTrendAggregationResult'] = None) -> None: + """ + Initialize a QueryAggregationQueryTrendAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `trend`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation + for the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation + that defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTrendAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.facet = facet + self.time_segments = time_segments + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTrendAggregation': + """Initialize a QueryAggregationQueryTrendAggregation object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'facet' in _dict: + args['facet'] = _dict.get('facet') + if 'time_segments' in _dict: + args['time_segments'] = _dict.get('time_segments') + if 'show_estimated_matching_results' in _dict: + args['show_estimated_matching_results'] = _dict.get( + 'show_estimated_matching_results') + if 'show_total_matching_documents' in _dict: + args['show_total_matching_documents'] = _dict.get( + 'show_total_matching_documents') + if 'results' in _dict: + args['results'] = [ + QueryTrendAggregationResult.from_dict(v) + for v in _dict.get('results') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryTrendAggregation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'facet') and self.facet is not None: + _dict['facet'] = self.facet + if hasattr(self, 'time_segments') and self.time_segments is not None: + _dict['time_segments'] = self.time_segments + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -9083,15 +13363,15 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTopHitsAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTrendAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTopHitsAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryTrendAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'QueryTopHitsAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryTrendAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index d24244403..448e78ec8 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on @@ -103,10 +103,13 @@ def list_languages(self, **kwargs) -> DetailedResponse: operation_id='list_languages') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/languages' @@ -168,13 +171,15 @@ def translate(self, operation_id='translate') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'text': text, 'model_id': model_id, 'source': source, - 'target': target + 'target': target, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data, ensure_ascii=False).encode('utf-8') @@ -182,6 +187,7 @@ def translate(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/translate' @@ -217,10 +223,13 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: operation_id='list_identifiable_languages') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/identifiable_languages' @@ -244,7 +253,7 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `IdentifiedLanguages` object """ - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -252,13 +261,16 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: operation_id='identify') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = text headers['content-type'] = 'text/plain' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/identify' @@ -310,11 +322,12 @@ def list_models(self, 'version': self.version, 'source': source, 'target': target, - 'default': default + 'default': default, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/models' @@ -330,7 +343,9 @@ def create_model(self, base_model_id: str, *, forced_glossary: BinaryIO = None, + forced_glossary_content_type: str = None, parallel_corpus: BinaryIO = None, + parallel_corpus_content_type: str = None, name: str = None, **kwargs) -> DetailedResponse: """ @@ -409,6 +424,8 @@ def create_model(self, words or short phrases. For more information, see **Supported file formats** in the method description. *With `curl`, use `--form forced_glossary=@{filename}`.*. + :param str forced_glossary_content_type: (optional) The content type of + forced_glossary. :param BinaryIO parallel_corpus: (optional) A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded @@ -420,6 +437,8 @@ def create_model(self, MB. For more information, see **Supported file formats** in the method description. *With `curl`, use `--form parallel_corpus=@{filename}`.*. + :param str parallel_corpus_content_type: (optional) The content type of + parallel_corpus. :param str name: (optional) An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 @@ -429,7 +448,7 @@ def create_model(self, :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ - if base_model_id is None: + if not base_model_id: raise ValueError('base_model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -440,19 +459,24 @@ def create_model(self, params = { 'version': self.version, 'base_model_id': base_model_id, - 'name': name + 'name': name, } form_data = [] if forced_glossary: - form_data.append(('forced_glossary', (None, forced_glossary, - 'application/octet-stream'))) + form_data.append( + ('forced_glossary', + (None, forced_glossary, forced_glossary_content_type or + 'application/octet-stream'))) if parallel_corpus: - form_data.append(('parallel_corpus', (None, parallel_corpus, - 'application/octet-stream'))) + form_data.append( + ('parallel_corpus', + (None, parallel_corpus, parallel_corpus_content_type or + 'application/octet-stream'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/models' @@ -477,7 +501,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `DeleteModelResult` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -485,10 +509,13 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='delete_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -508,8 +535,8 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: Get model details. Gets information about a translation model, including training status for custom - models. Use this API call to poll the status of your customization request. A - successfully completed training has a status of `available`. + models. Use this method to poll the status of your customization request. A + successfully completed training request has a status of `available`. :param str model_id: Model ID of the model to get. :param dict headers: A `dict` containing the request headers @@ -517,7 +544,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -525,10 +552,13 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='get_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -564,10 +594,13 @@ def list_documents(self, **kwargs) -> DetailedResponse: operation_id='list_documents') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/documents' @@ -593,17 +626,41 @@ def translate_document(self, Translate document. Submit a document for translation. You can submit the document contents in the - `file` parameter, or you can reference a previously submitted document by document + `file` parameter, or you can specify a previously submitted document by document ID. The maximum file size for document translation is - * 20 MB for service instances on the Standard, Advanced, and Premium plans - * 2 MB for service instances on the Lite plan. + * **2 MB** for service instances on the Lite plan + * **20 MB** for service instances on the Standard plan + * **50 MB** for service instances on the Advanced plan + * **150 MB** for service instances on the Premium plan + You can specify the format of the file to be translated in one of two ways: + * By specifying the appropriate file extension for the format. + * By specifying the content type (MIME type) of the format as the `type` of the + `file` parameter. + In some cases, especially for subtitle file formats, you must use either the file + extension or the content type. For more information about all supported file + formats, their file extensions and content types, and how and when to specify the + file extension or content type, see [Supported file + formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). + **Note:** When translating a previously submitted document, the target language + must be different from the target language of the original request when the + document was initially submitted. :param BinaryIO file: The contents of the source file to translate. The - maximum file size for document translation is 20 MB for service instances - on the Standard, Advanced, and Premium plans, and 2 MB for service - instances on the Lite plan. For more information, see [Supported file - formats - (Beta)](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). + maximum file size for document translation is + * **2 MB** for service instances on the Lite plan + * **20 MB** for service instances on the Standard plan + * **50 MB** for service instances on the Advanced plan + * **150 MB** for service instances on the Premium plan + You can specify the format of the file to be translated in one of two ways: + * By specifying the appropriate file extension for the format. + * By specifying the content type (MIME type) of the format as the `type` of + the `file` parameter. + In some cases, especially for subtitle file formats, you must use either + the file extension or the content type. + For more information about all supported file formats, their file + extensions and content types, and how and when to specify the file + extension or content type, see [Supported file + formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str model_id: (optional) The model to use for translation. For @@ -633,7 +690,9 @@ def translate_document(self, operation_id='translate_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if not filename and hasattr(file, 'name'): @@ -653,6 +712,7 @@ def translate_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/documents' @@ -678,7 +738,7 @@ def get_document_status(self, document_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object """ - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -686,10 +746,13 @@ def get_document_status(self, document_id: str, operation_id='get_document_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['document_id'] @@ -716,7 +779,7 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -724,10 +787,13 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: operation_id='delete_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['document_id'] path_param_values = self.encode_path_vars(document_id) @@ -772,18 +838,23 @@ def get_translated_document(self, :rtype: DetailedResponse with `BinaryIO` result """ - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'Accept': accept} + headers = { + 'Accept': accept, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='get_translated_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['document_id'] path_param_values = self.encode_path_vars(document_id) @@ -799,6 +870,34 @@ def get_translated_document(self, return response +class CreateModelEnums: + """ + Enums for create_model parameters. + """ + + class ForcedGlossaryContentType(str, Enum): + """ + The content type of forced_glossary. + """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' + APPLICATION_XLIFF_XML = 'application/xliff+xml' + TEXT_CSV = 'text/csv' + TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' + APPLICATION_JSON = 'application/json' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + + class ParallelCorpusContentType(str, Enum): + """ + The content type of parallel_corpus. + """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' + APPLICATION_XLIFF_XML = 'application/xliff+xml' + TEXT_CSV = 'text/csv' + TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' + APPLICATION_JSON = 'application/json' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + + class TranslateDocumentEnums: """ Enums for translate_document parameters. @@ -808,22 +907,25 @@ class FileContentType(str, Enum): """ The content type of file. """ - APPLICATION_POWERPOINT = 'application/powerpoint' APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_JSON = 'application/json' - APPLICATION_XML = 'application/xml' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_OCTET_STREAM = 'application/octet-stream' + APPLICATION_PDF = 'application/pdf' + APPLICATION_POWERPOINT = 'application/powerpoint' + APPLICATION_RTF = 'application/rtf' + APPLICATION_TTAF_XML = 'application/ttaf+xml' + APPLICATION_TTML_XML = 'application/ttml+xml' + APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' + APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' + APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_PDF = 'application/pdf' - APPLICATION_RTF = 'application/rtf' + APPLICATION_X_RTF = 'application/x-rtf' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + APPLICATION_XML = 'application/xml' TEXT_HTML = 'text/html' TEXT_JSON = 'text/json' TEXT_PLAIN = 'text/plain' @@ -831,7 +933,6 @@ class FileContentType(str, Enum): TEXT_RTF = 'text/rtf' TEXT_SBV = 'text/sbv' TEXT_SRT = 'text/srt' - TEXT_VTT = 'text/vtt' TEXT_XML = 'text/xml' @@ -966,7 +1067,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentList': args = {} if 'documents' in _dict: args['documents'] = [ - DocumentStatus.from_dict(x) for x in _dict.get('documents') + DocumentStatus.from_dict(v) for v in _dict.get('documents') ] else: raise ValueError( @@ -983,7 +1084,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = [x.to_dict() for x in self.documents] + documents_list = [] + for v in self.documents: + if isinstance(v, dict): + documents_list.append(v) + else: + documents_list.append(v.to_dict()) + _dict['documents'] = documents_list return _dict def _to_dict(self): @@ -1304,8 +1411,8 @@ def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': args = {} if 'languages' in _dict: args['languages'] = [ - IdentifiableLanguage.from_dict(x) - for x in _dict.get('languages') + IdentifiableLanguage.from_dict(v) + for v in _dict.get('languages') ] else: raise ValueError( @@ -1322,7 +1429,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] + languages_list = [] + for v in self.languages: + if isinstance(v, dict): + languages_list.append(v) + else: + languages_list.append(v.to_dict()) + _dict['languages'] = languages_list return _dict def _to_dict(self): @@ -1436,7 +1549,7 @@ def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': args = {} if 'languages' in _dict: args['languages'] = [ - IdentifiedLanguage.from_dict(x) for x in _dict.get('languages') + IdentifiedLanguage.from_dict(v) for v in _dict.get('languages') ] else: raise ValueError( @@ -1453,7 +1566,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] + languages_list = [] + for v in self.languages: + if isinstance(v, dict): + languages_list.append(v) + else: + languages_list.append(v.to_dict()) + _dict['languages'] = languages_list return _dict def _to_dict(self): @@ -1650,7 +1769,7 @@ def from_dict(cls, _dict: Dict) -> 'Languages': args = {} if 'languages' in _dict: args['languages'] = [ - Language.from_dict(x) for x in _dict.get('languages') + Language.from_dict(v) for v in _dict.get('languages') ] else: raise ValueError( @@ -1666,7 +1785,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] + languages_list = [] + for v in self.languages: + if isinstance(v, dict): + languages_list.append(v) + else: + languages_list.append(v.to_dict()) + _dict['languages'] = languages_list return _dict def _to_dict(self): @@ -1934,7 +2059,7 @@ def from_dict(cls, _dict: Dict) -> 'TranslationModels': args = {} if 'models' in _dict: args['models'] = [ - TranslationModel.from_dict(x) for x in _dict.get('models') + TranslationModel.from_dict(v) for v in _dict.get('models') ] else: raise ValueError( @@ -1951,7 +2076,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -2040,7 +2171,7 @@ def from_dict(cls, _dict: Dict) -> 'TranslationResult': 'detected_language_confidence') if 'translations' in _dict: args['translations'] = [ - Translation.from_dict(x) for x in _dict.get('translations') + Translation.from_dict(v) for v in _dict.get('translations') ] else: raise ValueError( @@ -2069,7 +2200,13 @@ def to_dict(self) -> Dict: _dict[ 'detected_language_confidence'] = self.detected_language_confidence if hasattr(self, 'translations') and self.translations is not None: - _dict['translations'] = [x.to_dict() for x in self.translations] + translations_list = [] + for v in self.translations: + if isinstance(v, dict): + translations_list.append(v) + else: + translations_list.append(v.to_dict()) + _dict['translations'] = translations_list return _dict def _to_dict(self): diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 0ae9da787..fd80a2695 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2017, 2022. +# (C) Copyright IBM Corp. 2017, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -24,6 +24,15 @@ models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. +IBM is sunsetting Watson Natural Language Understanding Custom Sentiment (BETA). From +**June 1, 2023** onward, you will no longer be able to use the Custom Sentiment +feature.

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

If you would like more +information or further guidance, please contact IBM Cloud Support.{: deprecated} API Version: 1.0 See: https://cloud.ibm.com/docs/natural-language-understanding @@ -62,7 +71,7 @@ def __init__( Construct a new client for the Natural Language Understanding service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-08-01`. + Specify dates in YYYY-MM-DD format. The current version is `2022-04-07`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -156,7 +165,9 @@ def analyze(self, operation_id='analyze') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'features': features, @@ -168,7 +179,7 @@ def analyze(self, 'fallback_to_raw': fallback_to_raw, 'return_analyzed_text': return_analyzed_text, 'language': language, - 'limit_text_characters': limit_text_characters + 'limit_text_characters': limit_text_characters, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -176,6 +187,7 @@ def analyze(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/analyze' @@ -211,10 +223,13 @@ def list_models(self, **kwargs) -> DetailedResponse: operation_id='list_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models' @@ -238,7 +253,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -246,10 +261,13 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='delete_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -264,276 +282,6 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - ######################### - # Manage sentiment models - ######################### - - def create_sentiment_model(self, - language: str, - training_data: BinaryIO, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: - """ - Create sentiment model. - - (Beta) Creates a custom sentiment model by uploading training data and associated - metadata. The model begins the training and deploying process and is ready to use - when the `status` is `available`. - - :param str language: The 2-letter language code of this model. - :param BinaryIO training_data: Training data in CSV format. For more - information, see [Sentiment training data - requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). - :param str name: (optional) An optional name for the model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if language is None: - raise ValueError('language must be provided') - if training_data is None: - raise ValueError('training_data must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - form_data.append(('language', (None, language, 'text/plain'))) - form_data.append(('training_data', (None, training_data, 'text/csv'))) - if name: - form_data.append(('name', (None, name, 'text/plain'))) - if description: - form_data.append(('description', (None, description, 'text/plain'))) - if model_version: - form_data.append( - ('model_version', (None, model_version, 'text/plain'))) - if workspace_id: - form_data.append( - ('workspace_id', (None, workspace_id, 'text/plain'))) - if version_description: - form_data.append(('version_description', (None, version_description, - 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/models/sentiment' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def list_sentiment_models(self, **kwargs) -> DetailedResponse: - """ - List sentiment models. - - (Beta) Returns all custom sentiment models associated with this service instance. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListSentimentModelsResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_sentiment_models') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/models/sentiment' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: - """ - Get sentiment model details. - - (Beta) Returns the status of the sentiment model with the given model ID. - - :param str model_id: ID of the model. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_sentiment_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: - """ - Update sentiment model. - - (Beta) Overwrites the training data associated with this custom sentiment model - and retrains the model. The new model replaces the current deployment. - - :param str model_id: ID of the model. - :param str language: The 2-letter language code of this model. - :param BinaryIO training_data: Training data in CSV format. For more - information, see [Sentiment training data - requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). - :param str name: (optional) An optional name for the model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - if language is None: - raise ValueError('language must be provided') - if training_data is None: - raise ValueError('training_data must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - form_data.append(('language', (None, language, 'text/plain'))) - form_data.append(('training_data', (None, training_data, 'text/csv'))) - if name: - form_data.append(('name', (None, name, 'text/plain'))) - if description: - form_data.append(('description', (None, description, 'text/plain'))) - if model_version: - form_data.append( - ('model_version', (None, model_version, 'text/plain'))) - if workspace_id: - form_data.append( - ('workspace_id', (None, workspace_id, 'text/plain'))) - if version_description: - form_data.append(('version_description', (None, version_description, - 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def delete_sentiment_model(self, model_id: str, - **kwargs) -> DetailedResponse: - """ - Delete sentiment model. - - (Beta) Un-deploys the custom sentiment model with the given model ID and deletes - all associated customer data, including any training data or binary artifacts. - - :param str model_id: ID of the model. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object - """ - - if model_id is None: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_sentiment_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - ######################### # Manage categories models ######################### @@ -541,8 +289,8 @@ def delete_sentiment_model(self, model_id: str, def create_categories_model(self, language: str, training_data: BinaryIO, + training_data_content_type: str, *, - training_data_content_type: str = None, name: str = None, description: str = None, model_version: str = None, @@ -573,17 +321,21 @@ def create_categories_model(self, :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -606,6 +358,7 @@ def create_categories_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/categories' @@ -635,10 +388,13 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: operation_id='list_categories_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/categories' @@ -662,7 +418,7 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -670,10 +426,13 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='get_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -692,8 +451,8 @@ def update_categories_model(self, model_id: str, language: str, training_data: BinaryIO, + training_data_content_type: str, *, - training_data_content_type: str = None, name: str = None, description: str = None, model_version: str = None, @@ -724,19 +483,23 @@ def update_categories_model(self, :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -759,6 +522,7 @@ def update_categories_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -788,7 +552,7 @@ def delete_categories_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -796,10 +560,13 @@ def delete_categories_model(self, model_id: str, operation_id='delete_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -818,17 +585,19 @@ def delete_categories_model(self, model_id: str, # Manage classifications models ######################### - def create_classifications_model(self, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def create_classifications_model( + self, + language: str, + training_data: BinaryIO, + training_data_content_type: str, + *, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + training_parameters: 'ClassificationsTrainingParameters' = None, + **kwargs) -> DetailedResponse: """ Create classifications model. @@ -848,15 +617,20 @@ def create_classifications_model(self, :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :param str version_description: (optional) The description of the version. + :param ClassificationsTrainingParameters training_parameters: (optional) + Optional classifications training parameters along with model train + requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, @@ -864,7 +638,9 @@ def create_classifications_model(self, operation_id='create_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -884,9 +660,14 @@ def create_classifications_model(self, if version_description: form_data.append(('version_description', (None, version_description, 'text/plain'))) + if training_parameters: + form_data.append( + ('training_parameters', (None, json.dumps(training_parameters), + 'application/json'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/classifications' @@ -917,10 +698,13 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: operation_id='list_classifications_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/classifications' @@ -945,7 +729,7 @@ def get_classifications_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -953,10 +737,13 @@ def get_classifications_model(self, model_id: str, operation_id='get_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -971,18 +758,20 @@ def get_classifications_model(self, model_id: str, response = self.send(request, **kwargs) return response - def update_classifications_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def update_classifications_model( + self, + model_id: str, + language: str, + training_data: BinaryIO, + training_data_content_type: str, + *, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + training_parameters: 'ClassificationsTrainingParameters' = None, + **kwargs) -> DetailedResponse: """ Update classifications model. @@ -1002,17 +791,22 @@ def update_classifications_model(self, :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :param str version_description: (optional) The description of the version. + :param ClassificationsTrainingParameters training_parameters: (optional) + Optional classifications training parameters along with model train + requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, @@ -1020,7 +814,9 @@ def update_classifications_model(self, operation_id='update_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -1040,9 +836,14 @@ def update_classifications_model(self, if version_description: form_data.append(('version_description', (None, version_description, 'text/plain'))) + if training_parameters: + form_data.append( + ('training_parameters', (None, json.dumps(training_parameters), + 'application/json'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -1072,7 +873,7 @@ def delete_classifications_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -1081,10 +882,13 @@ def delete_classifications_model(self, model_id: str, operation_id='delete_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -1266,24 +1070,24 @@ def from_dict(cls, _dict: Dict) -> 'AnalysisResults': args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) if 'concepts' in _dict: args['concepts'] = [ - ConceptsResult.from_dict(x) for x in _dict.get('concepts') + ConceptsResult.from_dict(v) for v in _dict.get('concepts') ] if 'entities' in _dict: args['entities'] = [ - EntitiesResult.from_dict(x) for x in _dict.get('entities') + EntitiesResult.from_dict(v) for v in _dict.get('entities') ] if 'keywords' in _dict: args['keywords'] = [ - KeywordsResult.from_dict(x) for x in _dict.get('keywords') + KeywordsResult.from_dict(v) for v in _dict.get('keywords') ] if 'categories' in _dict: args['categories'] = [ - CategoriesResult.from_dict(x) for x in _dict.get('categories') + CategoriesResult.from_dict(v) for v in _dict.get('categories') ] if 'classifications' in _dict: args['classifications'] = [ - ClassificationsResult.from_dict(x) - for x in _dict.get('classifications') + ClassificationsResult.from_dict(v) + for v in _dict.get('classifications') ] if 'emotion' in _dict: args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) @@ -1292,12 +1096,12 @@ def from_dict(cls, _dict: Dict) -> 'AnalysisResults': _dict.get('metadata')) if 'relations' in _dict: args['relations'] = [ - RelationsResult.from_dict(x) for x in _dict.get('relations') + RelationsResult.from_dict(v) for v in _dict.get('relations') ] if 'semantic_roles' in _dict: args['semantic_roles'] = [ - SemanticRolesResult.from_dict(x) - for x in _dict.get('semantic_roles') + SemanticRolesResult.from_dict(v) + for v in _dict.get('semantic_roles') ] if 'sentiment' in _dict: args['sentiment'] = SentimentResult.from_dict( @@ -1321,32 +1125,87 @@ def to_dict(self) -> Dict: if hasattr(self, 'retrieved_url') and self.retrieved_url is not None: _dict['retrieved_url'] = self.retrieved_url if hasattr(self, 'usage') and self.usage is not None: - _dict['usage'] = self.usage.to_dict() + if isinstance(self.usage, dict): + _dict['usage'] = self.usage + else: + _dict['usage'] = self.usage.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = [x.to_dict() for x in self.concepts] + concepts_list = [] + for v in self.concepts: + if isinstance(v, dict): + concepts_list.append(v) + else: + concepts_list.append(v.to_dict()) + _dict['concepts'] = concepts_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] + categories_list = [] + for v in self.categories: + if isinstance(v, dict): + categories_list.append(v) + else: + categories_list.append(v.to_dict()) + _dict['categories'] = categories_list if hasattr(self, 'classifications') and self.classifications is not None: - _dict['classifications'] = [ - x.to_dict() for x in self.classifications - ] + classifications_list = [] + for v in self.classifications: + if isinstance(v, dict): + classifications_list.append(v) + else: + classifications_list.append(v.to_dict()) + _dict['classifications'] = classifications_list if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() + if isinstance(self.metadata, dict): + _dict['metadata'] = self.metadata + else: + _dict['metadata'] = self.metadata.to_dict() if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = [x.to_dict() for x in self.relations] + relations_list = [] + for v in self.relations: + if isinstance(v, dict): + relations_list.append(v) + else: + relations_list.append(v.to_dict()) + _dict['relations'] = relations_list if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = [x.to_dict() for x in self.semantic_roles] + semantic_roles_list = [] + for v in self.semantic_roles: + if isinstance(v, dict): + semantic_roles_list.append(v) + else: + semantic_roles_list.append(v.to_dict()) + _dict['semantic_roles'] = semantic_roles_list if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax.to_dict() + if isinstance(self.syntax, dict): + _dict['syntax'] = self.syntax + else: + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -1620,7 +1479,7 @@ def from_dict(cls, _dict: Dict) -> 'CategoriesModel': ) if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] if 'last_trained' in _dict: args['last_trained'] = string_to_datetime(_dict.get('last_trained')) @@ -1662,7 +1521,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'last_trained') and self.last_trained is not None: _dict['last_trained'] = datetime_to_string(self.last_trained) if hasattr(self, 'last_deployed') and self.last_deployed is not None: @@ -1720,7 +1585,7 @@ def from_dict(cls, _dict: Dict) -> 'CategoriesModelList': args = {} if 'models' in _dict: args['models'] = [ - CategoriesModel.from_dict(x) for x in _dict.get('models') + CategoriesModel.from_dict(v) for v in _dict.get('models') ] return cls(**args) @@ -1733,7 +1598,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -1955,7 +1826,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'explanation') and self.explanation is not None: - _dict['explanation'] = self.explanation.to_dict() + if isinstance(self.explanation, dict): + _dict['explanation'] = self.explanation + else: + _dict['explanation'] = self.explanation.to_dict() return _dict def _to_dict(self): @@ -2006,8 +1880,8 @@ def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': args = {} if 'relevant_text' in _dict: args['relevant_text'] = [ - CategoriesRelevantText.from_dict(x) - for x in _dict.get('relevant_text') + CategoriesRelevantText.from_dict(v) + for v in _dict.get('relevant_text') ] return cls(**args) @@ -2020,7 +1894,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'relevant_text') and self.relevant_text is not None: - _dict['relevant_text'] = [x.to_dict() for x in self.relevant_text] + relevant_text_list = [] + for v in self.relevant_text: + if isinstance(v, dict): + relevant_text_list.append(v) + else: + relevant_text_list.append(v.to_dict()) + _dict['relevant_text'] = relevant_text_list return _dict def _to_dict(self): @@ -2166,7 +2046,7 @@ def from_dict(cls, _dict: Dict) -> 'ClassificationsModel': ) if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] if 'last_trained' in _dict: args['last_trained'] = string_to_datetime(_dict.get('last_trained')) @@ -2208,7 +2088,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'last_trained') and self.last_trained is not None: _dict['last_trained'] = datetime_to_string(self.last_trained) if hasattr(self, 'last_deployed') and self.last_deployed is not None: @@ -2267,7 +2153,7 @@ def from_dict(cls, _dict: Dict) -> 'ClassificationsModelList': args = {} if 'models' in _dict: args['models'] = [ - ClassificationsModel.from_dict(x) for x in _dict.get('models') + ClassificationsModel.from_dict(v) for v in _dict.get('models') ] return cls(**args) @@ -2280,7 +2166,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -2433,6 +2325,69 @@ def __ne__(self, other: 'ClassificationsResult') -> bool: return not self == other +class ClassificationsTrainingParameters(): + """ + Optional classifications training parameters along with model train requests. + + :attr str model_type: (optional) Model type selector to train either a + single_label or a multi_label classifier. + """ + + def __init__(self, *, model_type: str = None) -> None: + """ + Initialize a ClassificationsTrainingParameters object. + + :param str model_type: (optional) Model type selector to train either a + single_label or a multi_label classifier. + """ + self.model_type = model_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassificationsTrainingParameters': + """Initialize a ClassificationsTrainingParameters object from a json dictionary.""" + args = {} + if 'model_type' in _dict: + args['model_type'] = _dict.get('model_type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassificationsTrainingParameters object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'model_type') and self.model_type is not None: + _dict['model_type'] = self.model_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ClassificationsTrainingParameters object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassificationsTrainingParameters') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ClassificationsTrainingParameters') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ModelTypeEnum(str, Enum): + """ + Model type selector to train either a single_label or a multi_label classifier. + """ + SINGLE_LABEL = 'single_label' + MULTI_LABEL = 'multi_label' + + class ConceptsOptions(): """ Returns high-level concepts in the content. For example, a research paper about deep @@ -2731,7 +2686,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): @@ -2926,8 +2884,8 @@ def from_dict(cls, _dict: Dict) -> 'EmotionResult': _dict.get('document')) if 'targets' in _dict: args['targets'] = [ - TargetedEmotionResults.from_dict(x) - for x in _dict.get('targets') + TargetedEmotionResults.from_dict(v) + for v in _dict.get('targets') ] return cls(**args) @@ -2940,9 +2898,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() + if isinstance(self.document, dict): + _dict['document'] = self.document + else: + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x.to_dict() for x in self.targets] + targets_list = [] + for v in self.targets: + if isinstance(v, dict): + targets_list.append(v) + else: + targets_list.append(v.to_dict()) + _dict['targets'] = targets_list return _dict def _to_dict(self): @@ -3245,7 +3212,7 @@ def from_dict(cls, _dict: Dict) -> 'EntitiesResult': args['confidence'] = _dict.get('confidence') if 'mentions' in _dict: args['mentions'] = [ - EntityMention.from_dict(x) for x in _dict.get('mentions') + EntityMention.from_dict(v) for v in _dict.get('mentions') ] if 'count' in _dict: args['count'] = _dict.get('count') @@ -3276,15 +3243,30 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x.to_dict() for x in self.mentions] + mentions_list = [] + for v in self.mentions: + if isinstance(v, dict): + mentions_list.append(v) + else: + mentions_list.append(v.to_dict()) + _dict['mentions'] = mentions_list if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation.to_dict() + if isinstance(self.disambiguation, dict): + _dict['disambiguation'] = self.disambiguation + else: + _dict['disambiguation'] = self.disambiguation.to_dict() return _dict def _to_dict(self): @@ -3492,6 +3474,7 @@ class Features(): :attr SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. + Supported regions: Dallas region only. :attr CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, @@ -3564,6 +3547,7 @@ def __init__(self, :param SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. + Supported regions: Dallas region only. :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, @@ -3630,29 +3614,62 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'classifications') and self.classifications is not None: - _dict['classifications'] = self.classifications.to_dict() + if isinstance(self.classifications, dict): + _dict['classifications'] = self.classifications + else: + _dict['classifications'] = self.classifications.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts.to_dict() + if isinstance(self.concepts, dict): + _dict['concepts'] = self.concepts + else: + _dict['concepts'] = self.concepts.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities.to_dict() + if isinstance(self.entities, dict): + _dict['entities'] = self.entities + else: + _dict['entities'] = self.entities.to_dict() if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords.to_dict() + if isinstance(self.keywords, dict): + _dict['keywords'] = self.keywords + else: + _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations.to_dict() + if isinstance(self.relations, dict): + _dict['relations'] = self.relations + else: + _dict['relations'] = self.relations.to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles.to_dict() + if isinstance(self.semantic_roles, dict): + _dict['semantic_roles'] = self.semantic_roles + else: + _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'summarization') and self.summarization is not None: - _dict['summarization'] = self.summarization.to_dict() + if isinstance(self.summarization, dict): + _dict['summarization'] = self.summarization + else: + _dict['summarization'] = self.summarization.to_dict() if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories.to_dict() + if isinstance(self.categories, dict): + _dict['categories'] = self.categories + else: + _dict['categories'] = self.categories.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax.to_dict() + if isinstance(self.syntax, dict): + _dict['syntax'] = self.syntax + else: + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -3715,7 +3732,7 @@ def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': args = {} if 'authors' in _dict: args['authors'] = [ - Author.from_dict(x) for x in _dict.get('authors') + Author.from_dict(v) for v in _dict.get('authors') ] if 'publication_date' in _dict: args['publication_date'] = _dict.get('publication_date') @@ -3724,7 +3741,7 @@ def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': if 'image' in _dict: args['image'] = _dict.get('image') if 'feeds' in _dict: - args['feeds'] = [Feed.from_dict(x) for x in _dict.get('feeds')] + args['feeds'] = [Feed.from_dict(v) for v in _dict.get('feeds')] return cls(**args) @classmethod @@ -3736,7 +3753,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'authors') and self.authors is not None: - _dict['authors'] = [x.to_dict() for x in self.authors] + authors_list = [] + for v in self.authors: + if isinstance(v, dict): + authors_list.append(v) + else: + authors_list.append(v.to_dict()) + _dict['authors'] = authors_list if hasattr(self, 'publication_date') and self.publication_date is not None: _dict['publication_date'] = self.publication_date @@ -3745,7 +3768,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image') and self.image is not None: _dict['image'] = self.image if hasattr(self, 'feeds') and self.feeds is not None: - _dict['feeds'] = [x.to_dict() for x in self.feeds] + feeds_list = [] + for v in self.feeds: + if isinstance(v, dict): + feeds_list.append(v) + else: + feeds_list.append(v.to_dict()) + _dict['feeds'] = feeds_list return _dict def _to_dict(self): @@ -3972,9 +4001,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() return _dict def _to_dict(self): @@ -4016,7 +4051,7 @@ def from_dict(cls, _dict: Dict) -> 'ListModelsResults': """Initialize a ListModelsResults object from a json dictionary.""" args = {} if 'models' in _dict: - args['models'] = [Model.from_dict(x) for x in _dict.get('models')] + args['models'] = [Model.from_dict(v) for v in _dict.get('models')] return cls(**args) @classmethod @@ -4028,7 +4063,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -4050,62 +4091,6 @@ def __ne__(self, other: 'ListModelsResults') -> bool: return not self == other -class ListSentimentModelsResponse(): - """ - ListSentimentModelsResponse. - - :attr List[SentimentModel] models: (optional) - """ - - def __init__(self, *, models: List['SentimentModel'] = None) -> None: - """ - Initialize a ListSentimentModelsResponse object. - - :param List[SentimentModel] models: (optional) - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListSentimentModelsResponse': - """Initialize a ListSentimentModelsResponse object from a json dictionary.""" - args = {} - if 'models' in _dict: - args['models'] = [ - SentimentModel.from_dict(x) for x in _dict.get('models') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListSentimentModelsResponse object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListSentimentModelsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListSentimentModelsResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'ListSentimentModelsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Model(): """ Model. @@ -4120,7 +4105,7 @@ class Model(): that deployed this model to Natural Language Understanding. :attr str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :attr str version: (optional) Deprecated — use `model_version`. + :attr str version: (optional) Deprecated: Deprecated — use `model_version`. :attr str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :attr datetime created: (optional) A dateTime indicating when the model was @@ -4151,7 +4136,8 @@ def __init__(self, workspace that deployed this model to Natural Language Understanding. :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :param str version: (optional) Deprecated — use `model_version`. + :param str version: (optional) Deprecated: Deprecated — use + `model_version`. :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :param datetime created: (optional) A dateTime indicating when the model @@ -4339,7 +4325,7 @@ def from_dict(cls, _dict: Dict) -> 'RelationArgument': args = {} if 'entities' in _dict: args['entities'] = [ - RelationEntity.from_dict(x) for x in _dict.get('entities') + RelationEntity.from_dict(v) for v in _dict.get('entities') ] if 'location' in _dict: args['location'] = _dict.get('location') @@ -4356,7 +4342,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'text') and self.text is not None: @@ -4551,7 +4543,7 @@ def from_dict(cls, _dict: Dict) -> 'RelationsResult': args['type'] = _dict.get('type') if 'arguments' in _dict: args['arguments'] = [ - RelationArgument.from_dict(x) for x in _dict.get('arguments') + RelationArgument.from_dict(v) for v in _dict.get('arguments') ] return cls(**args) @@ -4570,7 +4562,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'arguments') and self.arguments is not None: - _dict['arguments'] = [x.to_dict() for x in self.arguments] + arguments_list = [] + for v in self.arguments: + if isinstance(v, dict): + arguments_list.append(v) + else: + arguments_list.append(v.to_dict()) + _dict['arguments'] = arguments_list return _dict def _to_dict(self): @@ -4850,11 +4848,20 @@ def to_dict(self) -> Dict: if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: - _dict['subject'] = self.subject.to_dict() + if isinstance(self.subject, dict): + _dict['subject'] = self.subject + else: + _dict['subject'] = self.subject.to_dict() if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action.to_dict() + if isinstance(self.action, dict): + _dict['action'] = self.action + else: + _dict['action'] = self.action.to_dict() if hasattr(self, 'object') and self.object is not None: - _dict['object'] = self.object.to_dict() + if isinstance(self.object, dict): + _dict['object'] = self.object + else: + _dict['object'] = self.object.to_dict() return _dict def _to_dict(self): @@ -4926,7 +4933,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'normalized') and self.normalized is not None: _dict['normalized'] = self.normalized if hasattr(self, 'verb') and self.verb is not None: - _dict['verb'] = self.verb.to_dict() + if isinstance(self.verb, dict): + _dict['verb'] = self.verb + else: + _dict['verb'] = self.verb.to_dict() return _dict def _to_dict(self): @@ -4979,7 +4989,7 @@ def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': args['text'] = _dict.get('text') if 'keywords' in _dict: args['keywords'] = [ - SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') ] return cls(**args) @@ -4994,7 +5004,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list return _dict def _to_dict(self): @@ -5053,11 +5069,11 @@ def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': args['text'] = _dict.get('text') if 'entities' in _dict: args['entities'] = [ - SemanticRolesEntity.from_dict(x) for x in _dict.get('entities') + SemanticRolesEntity.from_dict(v) for v in _dict.get('entities') ] if 'keywords' in _dict: args['keywords'] = [ - SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') ] return cls(**args) @@ -5072,9 +5088,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list return _dict def _to_dict(self): @@ -5220,196 +5248,6 @@ def __ne__(self, other: 'SentenceResult') -> bool: return not self == other -class SentimentModel(): - """ - SentimentModel. - - :attr List[str] features: (optional) The service features that are supported by - the custom model. - :attr str status: (optional) When the status is `available`, the model is ready - to use. - :attr str model_id: (optional) Unique model ID. - :attr datetime created: (optional) dateTime indicating when the model was - created. - :attr datetime last_trained: (optional) dateTime of last successful model - training. - :attr datetime last_deployed: (optional) dateTime of last successful model - deployment. - :attr str name: (optional) A name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: (optional) The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr List[Notice] notices: (optional) - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace - that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - """ - - def __init__(self, - *, - features: List[str] = None, - status: str = None, - model_id: str = None, - created: datetime = None, - last_trained: datetime = None, - last_deployed: datetime = None, - name: str = None, - user_metadata: dict = None, - language: str = None, - description: str = None, - model_version: str = None, - notices: List['Notice'] = None, - workspace_id: str = None, - version_description: str = None) -> None: - """ - Initialize a SentimentModel object. - - :param List[str] features: (optional) The service features that are - supported by the custom model. - :param str status: (optional) When the status is `available`, the model is - ready to use. - :param str model_id: (optional) Unique model ID. - :param datetime created: (optional) dateTime indicating when the model was - created. - :param datetime last_trained: (optional) dateTime of last successful model - training. - :param datetime last_deployed: (optional) dateTime of last successful model - deployment. - :param str name: (optional) A name for the model. - :param dict user_metadata: (optional) An optional map of metadata key-value - pairs to store with this model. - :param str language: (optional) The 2-letter language code of this model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param List[Notice] notices: (optional) - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - """ - self.features = features - self.status = status - self.model_id = model_id - self.created = created - self.last_trained = last_trained - self.last_deployed = last_deployed - self.name = name - self.user_metadata = user_metadata - self.language = language - self.description = description - self.model_version = model_version - self.notices = notices - self.workspace_id = workspace_id - self.version_description = version_description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SentimentModel': - """Initialize a SentimentModel object from a json dictionary.""" - args = {} - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SentimentModel object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'features') and self.features is not None: - _dict['features'] = self.features - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'last_trained') and self.last_trained is not None: - _dict['last_trained'] = datetime_to_string(self.last_trained) - if hasattr(self, 'last_deployed') and self.last_deployed is not None: - _dict['last_deployed'] = datetime_to_string(self.last_deployed) - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'user_metadata') and self.user_metadata is not None: - _dict['user_metadata'] = self.user_metadata - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - if hasattr(self, 'workspace_id') and self.workspace_id is not None: - _dict['workspace_id'] = self.workspace_id - if hasattr( - self, - 'version_description') and self.version_description is not None: - _dict['version_description'] = self.version_description - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SentimentModel object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SentimentModel') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SentimentModel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - When the status is `available`, the model is ready to use. - """ - STARTING = 'starting' - TRAINING = 'training' - DEPLOYING = 'deploying' - AVAILABLE = 'available' - ERROR = 'error' - DELETED = 'deleted' - - class SentimentOptions(): """ Analyzes the general sentiment of your content or the sentiment toward specific target @@ -5422,18 +5260,12 @@ class SentimentOptions(): sentiment results. :attr List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. - :attr str model: (optional) (Beta) Enter a [custom - model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard sentiment model for all sentiment analysis - operations in the request, including targeted sentiment for entities and - keywords. """ def __init__(self, *, document: bool = None, - targets: List[str] = None, - model: str = None) -> None: + targets: List[str] = None) -> None: """ Initialize a SentimentOptions object. @@ -5441,15 +5273,9 @@ def __init__(self, sentiment results. :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. - :param str model: (optional) (Beta) Enter a [custom - model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard sentiment model for all sentiment analysis - operations in the request, including targeted sentiment for entities and - keywords. """ self.document = document self.targets = targets - self.model = model @classmethod def from_dict(cls, _dict: Dict) -> 'SentimentOptions': @@ -5459,8 +5285,6 @@ def from_dict(cls, _dict: Dict) -> 'SentimentOptions': args['document'] = _dict.get('document') if 'targets' in _dict: args['targets'] = _dict.get('targets') - if 'model' in _dict: - args['model'] = _dict.get('model') return cls(**args) @classmethod @@ -5475,8 +5299,6 @@ def to_dict(self) -> Dict: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model return _dict def _to_dict(self): @@ -5532,8 +5354,8 @@ def from_dict(cls, _dict: Dict) -> 'SentimentResult': _dict.get('document')) if 'targets' in _dict: args['targets'] = [ - TargetedSentimentResults.from_dict(x) - for x in _dict.get('targets') + TargetedSentimentResults.from_dict(v) + for v in _dict.get('targets') ] return cls(**args) @@ -5546,9 +5368,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() + if isinstance(self.document, dict): + _dict['document'] = self.document + else: + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x.to_dict() for x in self.targets] + targets_list = [] + for v in self.targets: + if isinstance(v, dict): + targets_list.append(v) + else: + targets_list.append(v.to_dict()) + _dict['targets'] = targets_list return _dict def _to_dict(self): @@ -5574,6 +5405,7 @@ class SummarizationOptions(): """ (Experimental) Returns a summary of content. Supported languages: English only. + Supported regions: Dallas region only. :attr int limit: (optional) Maximum number of summary sentences to return. """ @@ -5667,7 +5499,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = self.tokens.to_dict() + if isinstance(self.tokens, dict): + _dict['tokens'] = self.tokens + else: + _dict['tokens'] = self.tokens.to_dict() if hasattr(self, 'sentences') and self.sentences is not None: _dict['sentences'] = self.sentences return _dict @@ -5786,11 +5621,11 @@ def from_dict(cls, _dict: Dict) -> 'SyntaxResult': args = {} if 'tokens' in _dict: args['tokens'] = [ - TokenResult.from_dict(x) for x in _dict.get('tokens') + TokenResult.from_dict(v) for v in _dict.get('tokens') ] if 'sentences' in _dict: args['sentences'] = [ - SentenceResult.from_dict(x) for x in _dict.get('sentences') + SentenceResult.from_dict(v) for v in _dict.get('sentences') ] return cls(**args) @@ -5803,9 +5638,21 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = [x.to_dict() for x in self.tokens] + tokens_list = [] + for v in self.tokens: + if isinstance(v, dict): + tokens_list.append(v) + else: + tokens_list.append(v.to_dict()) + _dict['tokens'] = tokens_list if hasattr(self, 'sentences') and self.sentences is not None: - _dict['sentences'] = [x.to_dict() for x in self.sentences] + sentences_list = [] + for v in self.sentences: + if isinstance(v, dict): + sentences_list.append(v) + else: + sentences_list.append(v.to_dict()) + _dict['sentences'] = sentences_list return _dict def _to_dict(self): @@ -5870,7 +5717,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index c769fb495..7d35d6eb5 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,10 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's -speech-recognition capabilities to produce transcripts of spoken audio. The service can +speech-recognition capabilities to produce transcripts of spoken audio. The service can transcribe speech from various languages and audio formats. In addition to basic transcription, the service can produce detailed information about many different aspects of the audio. It returns all JSON response content in the UTF-8 character set. @@ -27,11 +27,10 @@ have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum sampling rates of 8 kHz. The next-generation models offer high throughput and greater transcription accuracy. -Effective 15 March 2022, previous-generation models for all languages other than Arabic -and Japanese are deprecated. The deprecated models remain available until 15 September -2022, when they will be removed from the service and the documentation. You must migrate -to the equivalent next-generation model by the end of service date. For more information, -see [Migrating to next-generation +Effective **31 July 2023**, all previous-generation models will be removed from the +service and the documentation. Most previous-generation models were deprecated on 15 March +2022. You must migrate to the equivalent next-generation model by 31 July 2023. For more +information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).{: deprecated} For speech recognition, the service supports synchronous and asynchronous HTTP @@ -120,6 +119,7 @@ def list_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models' @@ -139,15 +139,13 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list#models-list-specific). :param str model_id: The identifier of the model in the form of its name - from the output of the [List models](#listmodels) method. (**Note:** The - model `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` - instead.). + from the output of the [List models](#listmodels) method. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -157,6 +155,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -191,7 +190,6 @@ def recognize(self, profanity_filter: bool = None, smart_formatting: bool = None, speaker_labels: bool = None, - customization_id: str = None, grammar_name: str = None, redaction: bool = None, audio_metrics: bool = None, @@ -200,6 +198,7 @@ def recognize(self, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, low_latency: bool = None, + character_insertion_bias: float = None, **kwargs) -> DetailedResponse: """ Recognize audio. @@ -267,15 +266,21 @@ def recognize(self, use next-generation models, the service can return transcriptions more quickly and also provide noticeably better transcription accuracy. You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Many next-generation models also support the - `low_latency` parameter, which is not available with previous-generation models. - Next-generation models do not support all of the parameters that are available for - use with previous-generation models. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + do a previous-generation model. Most next-generation models support the + `low_latency` parameter, and all next-generation models support the + `character_insertion_bias` parameter. These parameters are not available with + previous-generation models. + Next-generation models do not support all of the speech recognition parameters + that are available for use with previous-generation models. Next-generation models + do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** @@ -302,11 +307,17 @@ def recognize(self, :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. - :param str model: (optional) The identifier of the model that is to be used - for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for - speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + :param str model: (optional) The model to use for speech recognition. If + you omit the `model` parameter, the service uses the US English + `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_BroadbandModel`, you must either specify a model with the request or + specify a new default model for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). :param str language_customization_id: (optional) The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match @@ -339,14 +350,18 @@ def recognize(self, to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization - weight was specified for the custom model when it was trained, the default - value is 0.3. A customization weight that you specify overrides a weight - that was specified when the custom model was trained. - The default value yields the best performance in general. Assign a higher - value if your audio makes frequent use of OOV words from the custom model. - Use caution when setting the weight: a higher value can improve the - accuracy of phrases from the custom model's domain, but it can negatively - affect performance on non-domain phrases. + weight was specified for the custom model when the model was trained, the + default value is: + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models + A customization weight that you specify overrides a weight that was + specified when the custom model was trained. The default value yields the + best performance in general. Assign a higher value if your audio makes + frequent use of OOV words from the custom model. Use caution when setting + the weight: a higher value can improve the accuracy of phrases from the + custom model's domain, but it can negatively affect performance on + non-domain phrases. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :param int inactivity_timeout: (optional) The time in seconds after which, @@ -424,10 +439,6 @@ def recognize(self, Spanish transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). - :param str customization_id: (optional) **Deprecated.** Use the - `language_customization_id` parameter to specify the customization ID - (GUID) of a custom language model that is to be used with the recognition - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -457,12 +468,12 @@ def recognize(self, default, the service returns no audio metrics. See [Audio metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio-metrics). - :param float end_of_phrase_silence_time: (optional) If `true`, specifies - the duration of the pause interval at which the service splits a transcript - into multiple final results. If the service detects pauses or extended - silence before it reaches the end of the audio stream, its response can - include multiple final results. Silence indicates a point at which the - speaker pauses between spoken words or phrases. + :param float end_of_phrase_silence_time: (optional) Specifies the duration + of the pause interval at which the service splits a transcript into + multiple final results. If the service detects pauses or extended silence + before it reaches the end of the audio stream, its response can include + multiple final results. Silence indicates a point at which the speaker + pauses between spoken words or phrases. Specify a value for the pause interval in the range of 0.0 to 120.0. * A value greater than 0 specifies the interval that the service is to use for speech recognition. @@ -496,7 +507,9 @@ def recognize(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) @@ -511,7 +524,9 @@ def recognize(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) @@ -525,12 +540,31 @@ def recognize(self, to produce results even more quickly, though the results might be less accurate when the parameter is used. The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available only for some next-generation models. - For a list of next-generation models that support low latency, see + `Narrowband` models. It is available for most next-generation models. + * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For next-generation + models, an indication of whether the service is biased to recognize shorter + or longer strings of characters when developing transcription hypotheses. + By default, the service is optimized to produce the best balance of strings + of different lengths. + The default bias is 0.0. The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechRecognitionResults` object @@ -538,7 +572,9 @@ def recognize(self, if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} + headers = { + 'Content-Type': content_type, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='recognize') @@ -560,7 +596,6 @@ def recognize(self, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, 'speaker_labels': speaker_labels, - 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, 'audio_metrics': audio_metrics, @@ -568,13 +603,15 @@ def recognize(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias, } data = audio if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognize' @@ -645,7 +682,7 @@ def register_callback(self, :rtype: DetailedResponse with `dict` result representing a `RegisterStatus` object """ - if callback_url is None: + if not callback_url: raise ValueError('callback_url must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -653,10 +690,14 @@ def register_callback(self, operation_id='register_callback') headers.update(sdk_headers) - params = {'callback_url': callback_url, 'user_secret': user_secret} + params = { + 'callback_url': callback_url, + 'user_secret': user_secret, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/register_callback' @@ -686,7 +727,7 @@ def unregister_callback(self, callback_url: str, :rtype: DetailedResponse """ - if callback_url is None: + if not callback_url: raise ValueError('callback_url must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -694,10 +735,13 @@ def unregister_callback(self, callback_url: str, operation_id='unregister_callback') headers.update(sdk_headers) - params = {'callback_url': callback_url} + params = { + 'callback_url': callback_url, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/unregister_callback' request = self.prepare_request(method='POST', @@ -731,7 +775,6 @@ def create_job(self, profanity_filter: bool = None, smart_formatting: bool = None, speaker_labels: bool = None, - customization_id: str = None, grammar_name: str = None, redaction: bool = None, processing_metrics: bool = None, @@ -742,6 +785,7 @@ def create_job(self, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, low_latency: bool = None, + character_insertion_bias: float = None, **kwargs) -> DetailedResponse: """ Create a job. @@ -835,15 +879,21 @@ def create_job(self, use next-generation models, the service can return transcriptions more quickly and also provide noticeably better transcription accuracy. You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Many next-generation models also support the - `low_latency` parameter, which is not available with previous-generation models. - Next-generation models do not support all of the parameters that are available for - use with previous-generation models. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + do a previous-generation model. Most next-generation models support the + `low_latency` parameter, and all next-generation models support the + `character_insertion_bias` parameter. These parameters are not available with + previous-generation models. + Next-generation models do not support all of the speech recognition parameters + that are available for use with previous-generation models. Next-generation models + do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** @@ -856,11 +906,17 @@ def create_job(self, :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. - :param str model: (optional) The identifier of the model that is to be used - for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for - speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + :param str model: (optional) The model to use for speech recognition. If + you omit the `model` parameter, the service uses the US English + `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_BroadbandModel`, you must either specify a model with the request or + specify a new default model for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully allowlisted by using the [Register a callback](#registercallback) method. You can include the @@ -929,14 +985,18 @@ def create_job(self, to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization - weight was specified for the custom model when it was trained, the default - value is 0.3. A customization weight that you specify overrides a weight - that was specified when the custom model was trained. - The default value yields the best performance in general. Assign a higher - value if your audio makes frequent use of OOV words from the custom model. - Use caution when setting the weight: a higher value can improve the - accuracy of phrases from the custom model's domain, but it can negatively - affect performance on non-domain phrases. + weight was specified for the custom model when the model was trained, the + default value is: + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models + A customization weight that you specify overrides a weight that was + specified when the custom model was trained. The default value yields the + best performance in general. Assign a higher value if your audio makes + frequent use of OOV words from the custom model. Use caution when setting + the weight: a higher value can improve the accuracy of phrases from the + custom model's domain, but it can negatively affect performance on + non-domain phrases. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :param int inactivity_timeout: (optional) The time in seconds after which, @@ -1014,10 +1074,6 @@ def create_job(self, Spanish transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). - :param str customization_id: (optional) **Deprecated.** Use the - `language_customization_id` parameter to specify the customization ID - (GUID) of a custom language model that is to be used with the recognition - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -1069,12 +1125,12 @@ def create_job(self, default, the service returns no audio metrics. See [Audio metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio-metrics). - :param float end_of_phrase_silence_time: (optional) If `true`, specifies - the duration of the pause interval at which the service splits a transcript - into multiple final results. If the service detects pauses or extended - silence before it reaches the end of the audio stream, its response can - include multiple final results. Silence indicates a point at which the - speaker pauses between spoken words or phrases. + :param float end_of_phrase_silence_time: (optional) Specifies the duration + of the pause interval at which the service splits a transcript into + multiple final results. If the service detects pauses or extended silence + before it reaches the end of the audio stream, its response can include + multiple final results. Silence indicates a point at which the speaker + pauses between spoken words or phrases. Specify a value for the pause interval in the range of 0.0 to 120.0. * A value greater than 0 specifies the interval that the service is to use for speech recognition. @@ -1108,7 +1164,9 @@ def create_job(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) @@ -1123,7 +1181,9 @@ def create_job(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) @@ -1137,12 +1197,31 @@ def create_job(self, to produce results even more quickly, though the results might be less accurate when the parameter is used. The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available only for some next-generation models. - For a list of next-generation models that support low latency, see + `Narrowband` models. It is available for most next-generation models. + * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For next-generation + models, an indication of whether the service is biased to recognize shorter + or longer strings of characters when developing transcription hypotheses. + By default, the service is optimized to produce the best balance of strings + of different lengths. + The default bias is 0.0. The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object @@ -1150,7 +1229,9 @@ def create_job(self, if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} + headers = { + 'Content-Type': content_type, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_job') @@ -1176,7 +1257,6 @@ def create_job(self, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, 'speaker_labels': speaker_labels, - 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, 'processing_metrics': processing_metrics, @@ -1186,13 +1266,15 @@ def create_job(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias, } data = audio if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognitions' @@ -1233,6 +1315,7 @@ def check_jobs(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognitions' @@ -1266,7 +1349,7 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object """ - if id is None: + if not id: raise ValueError('id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1276,6 +1359,7 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['id'] @@ -1307,7 +1391,7 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if id is None: + if not id: raise ValueError('id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1317,6 +1401,7 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['id'] path_param_values = self.encode_path_vars(id) @@ -1351,11 +1436,10 @@ def create_language_model(self, The service returns an error if you attempt to create more than 1024 models. You do not lose any models, but you cannot create any more until your model count is below the limit. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** @@ -1365,10 +1449,12 @@ def create_language_model(self, customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :param str name: A user-defined name for the new custom language model. Use - a name that is unique among all custom language models that you own. Use a - localized name that matches the language of the custom model. Use a name + a localized name that matches the language of the custom model. Use a name that describes the domain of the custom model, such as `Medical custom - model` or `Legal custom model`. + model` or `Legal custom model`. Use a name that is unique among all custom + language models that you own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str base_model_name: The name of the base language model that is to be customized by the new custom language model. The new custom model can be used only with the base model that it customizes. @@ -1393,9 +1479,10 @@ def create_language_model(self, `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) All values that you pass for the `dialect` field are case-insensitive. - :param str description: (optional) A description of the new custom language - model. Use a localized description that matches the language of the custom - model. + :param str description: (optional) A recommended description of the new + custom language model. Use a localized description that matches the + language of the custom model. Include a maximum of 128 characters in the + description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object @@ -1415,7 +1502,7 @@ def create_language_model(self, 'name': name, 'base_model_name': base_model_name, 'dialect': dialect, - 'description': description + 'description': description, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1423,6 +1510,7 @@ def create_language_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -1457,8 +1545,7 @@ def list_language_models(self, five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). @@ -1473,10 +1560,13 @@ def list_language_models(self, operation_id='list_language_models') headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -1510,7 +1600,7 @@ def get_language_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1520,6 +1610,7 @@ def get_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1555,7 +1646,7 @@ def delete_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1565,6 +1656,7 @@ def delete_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1583,6 +1675,7 @@ def train_language_model(self, *, word_type_to_add: str = None, customization_weight: float = None, + strict: bool = None, **kwargs) -> DetailedResponse: """ Train a custom language model. @@ -1600,16 +1693,24 @@ def train_language_model(self, indicate that the training process has begun. You can monitor the status of the training by using the [Get a custom language model](#getlanguagemodel) method to poll the model's status. Use a loop to check - the status every 10 seconds. The method returns a `LanguageModel` object that - includes `status` and `progress` fields. A status of `available` means that the - custom model is trained and ready to use. The service cannot accept subsequent - training requests or requests to add new resources until the existing request - completes. + the status every 10 seconds. If you added custom words directly to a custom model + that is based on a next-generation model, allow for some minutes of extra training + time for the model. + The method returns a `LanguageModel` object that includes `status` and `progress` + fields. A status of `available` means that the custom model is trained and ready + to use. The service cannot accept subsequent training requests or requests to add + new resources until the existing request completes. + For custom models that are based on improved base language models, training also + performs an automatic upgrade to a newer version of the base model. You do not + need to use the [Upgrade a custom language model](#upgradelanguagemodel) method to + perform the upgrade. **See also:** - * [Train the custom language - model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) * [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) + * [Train the custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) + * [Upgrading custom language models that are based on improved next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng) ### Training failures Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as @@ -1641,7 +1742,10 @@ def train_language_model(self, weight for the custom language model. The customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for speech recognition. Specify a - value between 0.0 and 1.0; the default is 0.3. + value between 0.0 and 1.0. The default value is: + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the @@ -1652,12 +1756,18 @@ def train_language_model(self, customization weight for that request. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). + :param bool strict: (optional) If `false`, allows training of the custom + language model to proceed as long as the model contains at least one valid + resource. The method returns an array of `TrainingWarning` objects that + lists any invalid resources. By default (`true`), training of a custom + language model fails (status code 400) if the model contains one or more + invalid resources (corpus files, grammar files, or custom words). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1667,11 +1777,13 @@ def train_language_model(self, params = { 'word_type_to_add': word_type_to_add, - 'customization_weight': customization_weight + 'customization_weight': customization_weight, + 'strict': strict, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1713,7 +1825,7 @@ def reset_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1723,6 +1835,7 @@ def reset_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1755,11 +1868,17 @@ def upgrade_language_model(self, customization_id: str, upgrade is complete, the model resumes the status that it had prior to upgrade. The service cannot accept subsequent requests for the model until the upgrade completes. + For custom models that are based on improved base language models, the [Train a + custom language model](#trainlanguagemodel) method also performs an automatic + upgrade to a newer version of the base model. You do not need to use the upgrade + method. **See also:** + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) * [Upgrading a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language) - * [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). + * [Upgrading custom language models that are based on improved next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng). :param str customization_id: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the @@ -1770,7 +1889,7 @@ def upgrade_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1780,6 +1899,7 @@ def upgrade_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1817,7 +1937,7 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `Corpora` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1827,6 +1947,7 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1874,7 +1995,8 @@ def add_corpus(self, (OOV) words. After adding a corpus, you must validate the words resource to ensure that each OOV word's definition is complete and valid. You can use the [List custom words](#listwords) method to examine the words resource. You can use other - words method to eliminate typos and modify how words are pronounced as needed. + words method to eliminate typos and modify how words are pronounced and displayed + as needed. To add a corpus file that has the same name as an existing corpus, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing corpus causes the service to process the corpus text file and extract @@ -1938,9 +2060,9 @@ def add_corpus(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') if corpus_file is None: raise ValueError('corpus_file must be provided') @@ -1950,13 +2072,16 @@ def add_corpus(self, operation_id='add_corpus') headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } form_data = [] form_data.append(('corpus_file', (None, corpus_file, 'text/plain'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -1997,9 +2122,9 @@ def get_corpus(self, customization_id: str, corpus_name: str, :rtype: DetailedResponse with `dict` result representing a `Corpus` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2009,6 +2134,7 @@ def get_corpus(self, customization_id: str, corpus_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -2049,9 +2175,9 @@ def delete_corpus(self, customization_id: str, corpus_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2061,6 +2187,7 @@ def delete_corpus(self, customization_id: str, corpus_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -2092,10 +2219,13 @@ def list_words(self, all words from the custom model's words resource, only custom words that were added or modified by the user, or, _for a custom model that is based on a previous-generation model_, only out-of-vocabulary (OOV) words that were extracted - from corpora or are recognized by grammars. You can also indicate the order in - which the service is to return words; by default, the service lists words in - ascending alphabetical order. You must use credentials for the instance of the - service that owns a model to list information about its words. + from corpora or are recognized by grammars. _For a custom model that is based on a + next-generation model_, you can list all words or only those words that were added + directly by a user, which return the same results. + You can also indicate the order in which the service is to return words; by + default, the service lists words in ascending alphabetical order. You must use + credentials for the instance of the service that owns a model to list information + about its words. **See also:** [Listing words from a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#listWords). @@ -2127,7 +2257,7 @@ def list_words(self, :rtype: DetailedResponse with `dict` result representing a `Words` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2135,10 +2265,14 @@ def list_words(self, operation_id='list_words') headers.update(sdk_headers) - params = {'word_type': word_type, 'sort': sort} + params = { + 'word_type': word_type, + 'sort': sort, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2181,16 +2315,15 @@ def add_words(self, customization_id: str, words: List['CustomWord'], transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM` is to be displayed as `IBM™`. - * The `sounds_like` field, _which can be used only with a custom model that is - based on a previous-generation model_, provides an array of one or more - pronunciations for the word. Use the parameter to specify how the word can be - pronounced by users. Use the parameter for words that are difficult to pronounce, - foreign words, acronyms, and so on. For example, you might specify that the word - `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like - pronunciations for a word. If you omit the `sounds_like` field, the service - attempts to set the field to its pronunciation of the word. It cannot generate a - pronunciation for all words, so you must review the word's definition to ensure - that it is complete and valid. + * The `sounds_like` field provides an array of one or more pronunciations for the + word. Use the parameter to specify how the word can be pronounced by users. Use + the parameter for words that are difficult to pronounce, foreign words, acronyms, + and so on. For example, you might specify that the word `IEEE` can sound like `I + triple E`. You can specify a maximum of five sounds-like pronunciations for a + word. _For a custom model that is based on a previous-generation model_, if you + omit the `sounds_like` field, the service attempts to set the field to its + pronunciation of the word. It cannot generate a pronunciation for all words, so + you must review the word's definition to ensure that it is complete and valid. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error with the input data, it returns a failure code and @@ -2234,7 +2367,7 @@ def add_words(self, customization_id: str, words: List['CustomWord'], :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') @@ -2245,13 +2378,16 @@ def add_words(self, customization_id: str, words: List['CustomWord'], operation_id='add_words') headers.update(sdk_headers) - data = {'words': words} + data = { + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2299,16 +2435,15 @@ def add_word(self, transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM` is to be displayed as `IBM™`. - * The `sounds_like` field, _which can be used only with a custom model that is - based on a previous-generation model_, provides an array of one or more - pronunciations for the word. Use the parameter to specify how the word can be - pronounced by users. Use the parameter for words that are difficult to pronounce, - foreign words, acronyms, and so on. For example, you might specify that the word - `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like - pronunciations for a word. If you omit the `sounds_like` field, the service - attempts to set the field to its pronunciation of the word. It cannot generate a - pronunciation for all words, so you must review the word's definition to ensure - that it is complete and valid. + * The `sounds_like` field provides an array of one or more pronunciations for the + word. Use the parameter to specify how the word can be pronounced by users. Use + the parameter for words that are difficult to pronounce, foreign words, acronyms, + and so on. For example, you might specify that the word `IEEE` can sound like `i + triple e`. You can specify a maximum of five sounds-like pronunciations for a + word. _For custom models that are based on previous-generation models_, if you + omit the `sounds_like` field, the service attempts to set the field to its + pronunciation of the word. It cannot generate a pronunciation for all words, so + you must review the word's definition to ensure that it is complete and valid. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error, it does not add the word to the words resource. Use @@ -2340,34 +2475,34 @@ def add_word(self, custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the [Add a custom word](#addword) method. - :param List[str] sounds_like: (optional) _For a custom model that is based - on a previous-generation model_, an array of sounds-like pronunciations for - the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the - parameter to have the service automatically generate a sounds-like - pronunciation for the word. + :param List[str] sounds_like: (optional) As array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a + word that is not in the service's base vocabulary, omit the parameter to + have the service automatically generate a sounds-like pronunciation for the + word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this - field. Custom models based on next-generation models do not support the - `sounds_like` field. The service ignores the field. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service + uses the spelling of the word as the display-as value if you omit the + field. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2378,7 +2513,7 @@ def add_word(self, data = { 'word': word, 'sounds_like': sounds_like, - 'display_as': display_as + 'display_as': display_as, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2386,6 +2521,7 @@ def add_word(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2425,9 +2561,9 @@ def get_word(self, customization_id: str, word_name: str, :rtype: DetailedResponse with `dict` result representing a `Word` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2437,6 +2573,7 @@ def get_word(self, customization_id: str, word_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2477,9 +2614,9 @@ def delete_word(self, customization_id: str, word_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2489,6 +2626,7 @@ def delete_word(self, customization_id: str, word_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2532,7 +2670,7 @@ def list_grammars(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `Grammars` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2542,6 +2680,7 @@ def list_grammars(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2647,26 +2786,31 @@ def add_grammar(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') if grammar_file is None: raise ValueError('grammar_file must be provided') - if content_type is None: + if not content_type: raise ValueError('content_type must be provided') - headers = {'Content-Type': content_type} + headers = { + 'Content-Type': content_type, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_grammar') headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } data = grammar_file if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2711,9 +2855,9 @@ def get_grammar(self, customization_id: str, grammar_name: str, :rtype: DetailedResponse with `dict` result representing a `Grammar` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2723,6 +2867,7 @@ def get_grammar(self, customization_id: str, grammar_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2767,9 +2912,9 @@ def delete_grammar(self, customization_id: str, grammar_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2779,6 +2924,7 @@ def delete_grammar(self, customization_id: str, grammar_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2817,31 +2963,32 @@ def create_acoustic_model(self, below the limit. **Note:** Acoustic model customization is supported only for use with previous-generation models. It is not supported for next-generation models. - **Important:** Effective 15 March 2022, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). :param str name: A user-defined name for the new custom acoustic model. Use - a name that is unique among all custom acoustic models that you own. Use a - localized name that matches the language of the custom model. Use a name + a localized name that matches the language of the custom model. Use a name that describes the acoustic environment of the custom model, such as - `Mobile custom model` or `Noisy car custom model`. + `Mobile custom model` or `Noisy car custom model`. Use a name that is + unique among all custom acoustic models that you own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str base_model_name: The name of the base language model that is to be customized by the new custom acoustic model. The new custom model can be - used only with the base model that it customizes. (**Note:** The model - `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) + used only with the base model that it customizes. To determine whether a base model supports acoustic model customization, refer to [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). - :param str description: (optional) A description of the new custom acoustic - model. Use a localized description that matches the language of the custom - model. + :param str description: (optional) A recommended description of the new + custom acoustic model. Use a localized description that matches the + language of the custom model. Include a maximum of 128 characters in the + description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object @@ -2860,7 +3007,7 @@ def create_acoustic_model(self, data = { 'name': name, 'base_model_name': base_model_name, - 'description': description + 'description': description, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2868,6 +3015,7 @@ def create_acoustic_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' @@ -2901,8 +3049,7 @@ def list_acoustic_models(self, five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). @@ -2917,10 +3064,13 @@ def list_acoustic_models(self, operation_id='list_acoustic_models') headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' @@ -2953,7 +3103,7 @@ def get_acoustic_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2963,6 +3113,7 @@ def get_acoustic_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2998,7 +3149,7 @@ def delete_acoustic_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3008,6 +3159,7 @@ def delete_acoustic_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3026,6 +3178,7 @@ def train_acoustic_model(self, customization_id: str, *, custom_language_model_id: str = None, + strict: bool = None, **kwargs) -> DetailedResponse: """ Train a custom acoustic model. @@ -3071,8 +3224,13 @@ def train_acoustic_model(self, Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as another training request or a request to add audio resources to the model. - * The custom model contains less than 10 minutes or more than 200 hours of audio - data. + * The custom model contains less than 10 minutes of audio that includes speech, + not silence. + * The custom model contains more than 50 hours of audio (for IBM Cloud) or more + that 200 hours of audio (for IBM Cloud Pak for Data). **Note:** For IBM Cloud, the + maximum hours of audio for a custom acoustic model was reduced from 200 to 50 + hours in August and September 2022. For more information, see [Maximum hours of + audio](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audioResources#audioMaximum). * You passed a custom language model with the `custom_language_model_id` query parameter that is not in the available state. A custom language model must be fully trained and available to be used to train a custom acoustic model. @@ -3097,12 +3255,18 @@ def train_acoustic_model(self, custom acoustic model, and the custom language model must be fully trained and available. The credentials specified with the request must own both custom models. + :param bool strict: (optional) If `false`, allows training of the custom + acoustic model to proceed as long as the model contains at least one valid + audio resource. The method returns an array of `TrainingWarning` objects + that lists any invalid resources. By default (`true`), training of a custom + acoustic model fails (status code 400) if the model contains one or more + invalid audio resources. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3110,10 +3274,14 @@ def train_acoustic_model(self, operation_id='train_acoustic_model') headers.update(sdk_headers) - params = {'custom_language_model_id': custom_language_model_id} + params = { + 'custom_language_model_id': custom_language_model_id, + 'strict': strict, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3156,7 +3324,7 @@ def reset_acoustic_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3166,6 +3334,7 @@ def reset_acoustic_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3236,7 +3405,7 @@ def upgrade_acoustic_model(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3246,11 +3415,12 @@ def upgrade_acoustic_model(self, params = { 'custom_language_model_id': custom_language_model_id, - 'force': force + 'force': force, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3294,7 +3464,7 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `AudioResources` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3304,6 +3474,7 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3341,11 +3512,15 @@ def add_audio(self, You can use this method to add any number of audio resources to a custom model by calling the method once for each audio or archive file. You can add multiple different audio resources at the same time. You must add a minimum of 10 minutes - and a maximum of 200 hours of audio that includes speech, not just silence, to a - custom acoustic model before you can train it. No audio resource, audio- or - archive-type, can be larger than 100 MB. To add an audio resource that has the - same name as an existing audio resource, set the `allow_overwrite` parameter to - `true`; otherwise, the request fails. + of audio that includes speech, not just silence, to a custom acoustic model before + you can train it. No audio resource, audio- or archive-type, can be larger than + 100 MB. To add an audio resource that has the same name as an existing audio + resource, set the `allow_overwrite` parameter to `true`; otherwise, the request + fails. A custom model can contain no more than 50 hours of audio (for IBM Cloud) + or 200 hours of audio (for IBM Cloud Pak for Data). **Note:** For IBM Cloud, the + maximum hours of audio for a custom acoustic model was reduced from 200 to 50 + hours in August and September 2022. For more information, see [Maximum hours of + audio](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audioResources#audioMaximum). The method is asynchronous. It can take several seconds or minutes to complete depending on the duration of the audio and, in the case of an archive file, the total number of audio files being processed. The service returns a 201 response @@ -3464,27 +3639,30 @@ def add_audio(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') if audio_resource is None: raise ValueError('audio_resource must be provided') headers = { 'Content-Type': content_type, - 'Contained-Content-Type': contained_content_type + 'Contained-Content-Type': contained_content_type, } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_audio') headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } data = audio_resource if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3540,9 +3718,9 @@ def get_audio(self, customization_id: str, audio_name: str, :rtype: DetailedResponse with `dict` result representing a `AudioListing` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3552,6 +3730,7 @@ def get_audio(self, customization_id: str, audio_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3594,9 +3773,9 @@ def delete_audio(self, customization_id: str, audio_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3606,6 +3785,7 @@ def delete_audio(self, customization_id: str, audio_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3650,7 +3830,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3658,10 +3838,13 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'customer_id': customer_id} + params = { + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' request = self.prepare_request(method='DELETE', @@ -3681,10 +3864,8 @@ class GetModelEnums: class ModelId(str, Enum): """ The identifier of the model in the form of its name from the output of the [List - models](#listmodels) method. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.). + models](#listmodels) method. """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -3723,6 +3904,7 @@ class ModelId(str, Enum): ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' @@ -3732,21 +3914,26 @@ class ModelId(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -3781,12 +3968,17 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. - (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Using a model for speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + The model to use for speech recognition. If you omit the `model` parameter, the + service uses the US English `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, + you must either specify a model with the request or specify a new default model + for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -3825,6 +4017,7 @@ class Model(str, Enum): ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' @@ -3834,21 +4027,26 @@ class Model(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -3883,12 +4081,17 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. - (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Using a model for speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + The model to use for speech recognition. If you omit the `model` parameter, the + service uses the US English `en-US_BroadbandModel` by default. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, + you must either specify a model with the request or specify a new default model + for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [Using the default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -3927,6 +4130,7 @@ class Model(str, Enum): ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' @@ -3936,21 +4140,26 @@ class Model(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -3992,13 +4201,11 @@ class Language(str, Enum): are to be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or - custom acoustic models that are owned by the requesting credentials. (**Note:** - The identifier `ar-AR` is deprecated; use `ar-MS` instead.) + custom acoustic models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ - AR_AR = 'ar-AR' AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4023,6 +4230,7 @@ class Language(str, Enum): NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' + SV_SE = 'sv-SE' ZH_CN = 'zh-CN' @@ -4112,13 +4320,11 @@ class Language(str, Enum): are to be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or - custom acoustic models that are owned by the requesting credentials. (**Note:** - The identifier `ar-AR` is deprecated; use `ar-MS` instead.) + custom acoustic models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ - AR_AR = 'ar-AR' AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4143,6 +4349,7 @@ class Language(str, Enum): NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' + SV_SE = 'sv-SE' ZH_CN = 'zh-CN' @@ -4479,7 +4686,7 @@ def from_dict(cls, _dict: Dict) -> 'AcousticModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - AcousticModel.from_dict(x) for x in _dict.get('customizations') + AcousticModel.from_dict(v) for v in _dict.get('customizations') ] else: raise ValueError( @@ -4496,7 +4703,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -4740,7 +4953,7 @@ def from_dict(cls, _dict: Dict) -> 'AudioListing': args['container'] = AudioResource.from_dict(_dict.get('container')) if 'audio' in _dict: args['audio'] = [ - AudioResource.from_dict(x) for x in _dict.get('audio') + AudioResource.from_dict(v) for v in _dict.get('audio') ] return cls(**args) @@ -4757,13 +4970,25 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details.to_dict() + if isinstance(self.details, dict): + _dict['details'] = self.details + else: + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'container') and self.container is not None: - _dict['container'] = self.container.to_dict() + if isinstance(self.container, dict): + _dict['container'] = self.container + else: + _dict['container'] = self.container.to_dict() if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x.to_dict() for x in self.audio] + audio_list = [] + for v in self.audio: + if isinstance(v, dict): + audio_list.append(v) + else: + audio_list.append(v.to_dict()) + _dict['audio'] = audio_list return _dict def _to_dict(self): @@ -4862,7 +5087,10 @@ def to_dict(self) -> Dict: 'sampling_interval') and self.sampling_interval is not None: _dict['sampling_interval'] = self.sampling_interval if hasattr(self, 'accumulated') and self.accumulated is not None: - _dict['accumulated'] = self.accumulated.to_dict() + if isinstance(self.accumulated, dict): + _dict['accumulated'] = self.accumulated + else: + _dict['accumulated'] = self.accumulated.to_dict() return _dict def _to_dict(self): @@ -5030,8 +5258,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'direct_current_offset' in _dict: args['direct_current_offset'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('direct_current_offset') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('direct_current_offset') ] else: raise ValueError( @@ -5039,8 +5267,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'clipping_rate' in _dict: args['clipping_rate'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('clipping_rate') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('clipping_rate') ] else: raise ValueError( @@ -5048,8 +5276,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'speech_level' in _dict: args['speech_level'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('speech_level') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('speech_level') ] else: raise ValueError( @@ -5057,8 +5285,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'non_speech_level' in _dict: args['non_speech_level'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('non_speech_level') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('non_speech_level') ] else: raise ValueError( @@ -5089,18 +5317,38 @@ def to_dict(self) -> Dict: _dict['high_frequency_loss'] = self.high_frequency_loss if hasattr(self, 'direct_current_offset' ) and self.direct_current_offset is not None: - _dict['direct_current_offset'] = [ - x.to_dict() for x in self.direct_current_offset - ] + direct_current_offset_list = [] + for v in self.direct_current_offset: + if isinstance(v, dict): + direct_current_offset_list.append(v) + else: + direct_current_offset_list.append(v.to_dict()) + _dict['direct_current_offset'] = direct_current_offset_list if hasattr(self, 'clipping_rate') and self.clipping_rate is not None: - _dict['clipping_rate'] = [x.to_dict() for x in self.clipping_rate] + clipping_rate_list = [] + for v in self.clipping_rate: + if isinstance(v, dict): + clipping_rate_list.append(v) + else: + clipping_rate_list.append(v.to_dict()) + _dict['clipping_rate'] = clipping_rate_list if hasattr(self, 'speech_level') and self.speech_level is not None: - _dict['speech_level'] = [x.to_dict() for x in self.speech_level] + speech_level_list = [] + for v in self.speech_level: + if isinstance(v, dict): + speech_level_list.append(v) + else: + speech_level_list.append(v.to_dict()) + _dict['speech_level'] = speech_level_list if hasattr(self, 'non_speech_level') and self.non_speech_level is not None: - _dict['non_speech_level'] = [ - x.to_dict() for x in self.non_speech_level - ] + non_speech_level_list = [] + for v in self.non_speech_level: + if isinstance(v, dict): + non_speech_level_list.append(v) + else: + non_speech_level_list.append(v.to_dict()) + _dict['non_speech_level'] = non_speech_level_list return _dict def _to_dict(self): @@ -5302,7 +5550,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details.to_dict() + if isinstance(self.details, dict): + _dict['details'] = self.details + else: + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict @@ -5384,7 +5635,7 @@ def from_dict(cls, _dict: Dict) -> 'AudioResources': ) if 'audio' in _dict: args['audio'] = [ - AudioResource.from_dict(x) for x in _dict.get('audio') + AudioResource.from_dict(v) for v in _dict.get('audio') ] else: raise ValueError( @@ -5404,7 +5655,13 @@ def to_dict(self) -> Dict: ) and self.total_minutes_of_audio is not None: _dict['total_minutes_of_audio'] = self.total_minutes_of_audio if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x.to_dict() for x in self.audio] + audio_list = [] + for v in self.audio: + if isinstance(v, dict): + audio_list.append(v) + else: + audio_list.append(v.to_dict()) + _dict['audio'] = audio_list return _dict def _to_dict(self): @@ -5451,7 +5708,7 @@ def from_dict(cls, _dict: Dict) -> 'Corpora': args = {} if 'corpora' in _dict: args['corpora'] = [ - Corpus.from_dict(x) for x in _dict.get('corpora') + Corpus.from_dict(v) for v in _dict.get('corpora') ] else: raise ValueError( @@ -5467,7 +5724,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'corpora') and self.corpora is not None: - _dict['corpora'] = [x.to_dict() for x in self.corpora] + corpora_list = [] + for v in self.corpora: + if isinstance(v, dict): + corpora_list.append(v) + else: + corpora_list.append(v.to_dict()) + _dict['corpora'] = corpora_list return _dict def _to_dict(self): @@ -5641,26 +5904,24 @@ class CustomWord(): model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the [Add a custom word](#addword) method. - :attr List[str] sounds_like: (optional) _For a custom model that is based on a - previous-generation model_, an array of sounds-like pronunciations for the - custom word. Specify how words that are difficult to pronounce, foreign words, - acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the parameter to - have the service automatically generate a sounds-like pronunciation for the - word. + :attr List[str] sounds_like: (optional) As array of sounds-like pronunciations + for the custom word. Specify how words that are difficult to pronounce, foreign + words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a word + that is not in the service's base vocabulary, omit the parameter to have the + service automatically generate a sounds-like pronunciation for the word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this field. - Custom models based on next-generation models do not support the `sounds_like` - field. The service ignores the field. :attr str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service uses + the spelling of the word as the display-as value if you omit the field. """ def __init__(self, @@ -5676,26 +5937,26 @@ def __init__(self, custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the [Add a custom word](#addword) method. - :param List[str] sounds_like: (optional) _For a custom model that is based - on a previous-generation model_, an array of sounds-like pronunciations for - the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the - parameter to have the service automatically generate a sounds-like - pronunciation for the word. + :param List[str] sounds_like: (optional) As array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a + word that is not in the service's base vocabulary, omit the parameter to + have the service automatically generate a sounds-like pronunciation for the + word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this - field. Custom models based on next-generation models do not support the - `sounds_like` field. The service ignores the field. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service + uses the spelling of the word as the display-as value if you omit the + field. """ self.word = word self.sounds_like = sounds_like @@ -5906,7 +6167,7 @@ def from_dict(cls, _dict: Dict) -> 'Grammars': args = {} if 'grammars' in _dict: args['grammars'] = [ - Grammar.from_dict(x) for x in _dict.get('grammars') + Grammar.from_dict(v) for v in _dict.get('grammars') ] else: raise ValueError( @@ -5922,7 +6183,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'grammars') and self.grammars is not None: - _dict['grammars'] = [x.to_dict() for x in self.grammars] + grammars_list = [] + for v in self.grammars: + if isinstance(v, dict): + grammars_list.append(v) + else: + grammars_list.append(v.to_dict()) + _dict['grammars'] = grammars_list return _dict def _to_dict(self): @@ -6356,7 +6623,7 @@ def from_dict(cls, _dict: Dict) -> 'LanguageModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - LanguageModel.from_dict(x) for x in _dict.get('customizations') + LanguageModel.from_dict(v) for v in _dict.get('customizations') ] else: raise ValueError( @@ -6373,7 +6640,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -6617,7 +6890,10 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'processed_audio') and self.processed_audio is not None: - _dict['processed_audio'] = self.processed_audio.to_dict() + if isinstance(self.processed_audio, dict): + _dict['processed_audio'] = self.processed_audio + else: + _dict['processed_audio'] = self.processed_audio.to_dict() if hasattr(self, 'wall_clock_since_first_byte_received' ) and self.wall_clock_since_first_byte_received is not None: _dict[ @@ -6683,7 +6959,9 @@ class RecognitionJob(): message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field can be returned only by the - [Create a job](#createjob) method. + [Create a job](#createjob) method. (If you use the `character_insertion_bias` + parameter with a previous-generation model, the warning message refers to the + parameter as `lambdaBias`.). """ def __init__(self, @@ -6735,7 +7013,9 @@ def __init__(self, descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field - can be returned only by the [Create a job](#createjob) method. + can be returned only by the [Create a job](#createjob) method. (If you use + the `character_insertion_bias` parameter with a previous-generation model, + the warning message refers to the parameter as `lambdaBias`.). """ self.id = id self.status = status @@ -6775,8 +7055,8 @@ def from_dict(cls, _dict: Dict) -> 'RecognitionJob': args['user_token'] = _dict.get('user_token') if 'results' in _dict: args['results'] = [ - SpeechRecognitionResults.from_dict(x) - for x in _dict.get('results') + SpeechRecognitionResults.from_dict(v) + for v in _dict.get('results') ] if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') @@ -6803,7 +7083,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_token') and self.user_token is not None: _dict['user_token'] = self.user_token if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict @@ -6871,7 +7157,7 @@ def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': args = {} if 'recognitions' in _dict: args['recognitions'] = [ - RecognitionJob.from_dict(x) for x in _dict.get('recognitions') + RecognitionJob.from_dict(v) for v in _dict.get('recognitions') ] else: raise ValueError( @@ -6888,7 +7174,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'recognitions') and self.recognitions is not None: - _dict['recognitions'] = [x.to_dict() for x in self.recognitions] + recognitions_list = [] + for v in self.recognitions: + if isinstance(v, dict): + recognitions_list.append(v) + else: + recognitions_list.append(v.to_dict()) + _dict['recognitions'] = recognitions_list return _dict def _to_dict(self): @@ -7217,7 +7509,10 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features.to_dict() + if isinstance(self.supported_features, dict): + _dict['supported_features'] = self.supported_features + else: + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict @@ -7264,7 +7559,7 @@ def from_dict(cls, _dict: Dict) -> 'SpeechModels': args = {} if 'models' in _dict: args['models'] = [ - SpeechModel.from_dict(x) for x in _dict.get('models') + SpeechModel.from_dict(v) for v in _dict.get('models') ] else: raise ValueError( @@ -7280,7 +7575,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -7507,8 +7808,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': ) if 'alternatives' in _dict: args['alternatives'] = [ - SpeechRecognitionAlternative.from_dict(x) - for x in _dict.get('alternatives') + SpeechRecognitionAlternative.from_dict(v) + for v in _dict.get('alternatives') ] else: raise ValueError( @@ -7518,8 +7819,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': args['keywords_result'] = _dict.get('keywords_result') if 'word_alternatives' in _dict: args['word_alternatives'] = [ - WordAlternativeResults.from_dict(x) - for x in _dict.get('word_alternatives') + WordAlternativeResults.from_dict(v) + for v in _dict.get('word_alternatives') ] if 'end_of_utterance' in _dict: args['end_of_utterance'] = _dict.get('end_of_utterance') @@ -7536,15 +7837,25 @@ def to_dict(self) -> Dict: if hasattr(self, 'final') and self.final is not None: _dict['final'] = self.final if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list if hasattr(self, 'keywords_result') and self.keywords_result is not None: _dict['keywords_result'] = self.keywords_result if hasattr(self, 'word_alternatives') and self.word_alternatives is not None: - _dict['word_alternatives'] = [ - x.to_dict() for x in self.word_alternatives - ] + word_alternatives_list = [] + for v in self.word_alternatives: + if isinstance(v, dict): + word_alternatives_list.append(v) + else: + word_alternatives_list.append(v.to_dict()) + _dict['word_alternatives'] = word_alternatives_list if hasattr(self, 'end_of_utterance') and self.end_of_utterance is not None: _dict['end_of_utterance'] = self.end_of_utterance @@ -7624,7 +7935,9 @@ class SpeechRecognitionResults(): * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the form - `"{invalid_arg_1}, {invalid_arg_2}."` + `"{invalid_arg_1}, {invalid_arg_2}."` (If you use the `character_insertion_bias` + parameter with a previous-generation model, the warning message refers to the + parameter as `lambdaBias`.) * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your custom model has @@ -7681,7 +7994,9 @@ def __init__(self, * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the - form `"{invalid_arg_1}, {invalid_arg_2}."` + form `"{invalid_arg_1}, {invalid_arg_2}."` (If you use the + `character_insertion_bias` parameter with a previous-generation model, the + warning message refers to the parameter as `lambdaBias`.) * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your @@ -7704,15 +8019,15 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': args = {} if 'results' in _dict: args['results'] = [ - SpeechRecognitionResult.from_dict(x) - for x in _dict.get('results') + SpeechRecognitionResult.from_dict(v) + for v in _dict.get('results') ] if 'result_index' in _dict: args['result_index'] = _dict.get('result_index') if 'speaker_labels' in _dict: args['speaker_labels'] = [ - SpeakerLabelsResult.from_dict(x) - for x in _dict.get('speaker_labels') + SpeakerLabelsResult.from_dict(v) + for v in _dict.get('speaker_labels') ] if 'processing_metrics' in _dict: args['processing_metrics'] = ProcessingMetrics.from_dict( @@ -7733,17 +8048,35 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'result_index') and self.result_index is not None: _dict['result_index'] = self.result_index if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: - _dict['speaker_labels'] = [x.to_dict() for x in self.speaker_labels] + speaker_labels_list = [] + for v in self.speaker_labels: + if isinstance(v, dict): + speaker_labels_list.append(v) + else: + speaker_labels_list.append(v.to_dict()) + _dict['speaker_labels'] = speaker_labels_list if hasattr( self, 'processing_metrics') and self.processing_metrics is not None: - _dict['processing_metrics'] = self.processing_metrics.to_dict() + if isinstance(self.processing_metrics, dict): + _dict['processing_metrics'] = self.processing_metrics + else: + _dict['processing_metrics'] = self.processing_metrics.to_dict() if hasattr(self, 'audio_metrics') and self.audio_metrics is not None: - _dict['audio_metrics'] = self.audio_metrics.to_dict() + if isinstance(self.audio_metrics, dict): + _dict['audio_metrics'] = self.audio_metrics + else: + _dict['audio_metrics'] = self.audio_metrics.to_dict() if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict @@ -7924,7 +8257,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingResponse': args = {} if 'warnings' in _dict: args['warnings'] = [ - TrainingWarning.from_dict(x) for x in _dict.get('warnings') + TrainingWarning.from_dict(v) for v in _dict.get('warnings') ] return cls(**args) @@ -7937,7 +8270,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x.to_dict() for x in self.warnings] + warnings_list = [] + for v in self.warnings: + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list return _dict def _to_dict(self): @@ -8053,19 +8392,23 @@ class Word(): :attr str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :attr List[str] sounds_like: _For a custom model that is based on a - previous-generation model_, an array of as many as five pronunciations for the - word. The array can include the sounds-like pronunciation that is automatically - generated by the service if none is provided when the word is added to the - custom model; the service adds this pronunciation when it finishes processing - the word. - _For a custom model that is based on a next-generation model_, this field does - not apply. Custom models based on next-generation models do not support the - `sounds_like` field, which is ignored. + :attr List[str] sounds_like: An array of as many as five pronunciations for the + word. + * _For a custom model that is based on a previous-generation model_, in addition + to sounds-like pronunciations that were added by a user, the array can include a + sounds-like pronunciation that is automatically generated by the service if none + is provided when the word is added to the custom model. + * _For a custom model that is based on a next-generation model_, the array can + include only sounds-like pronunciations that were added by a user. :attr str display_as: The spelling of the word that the service uses to display - the word in a transcript. The field contains an empty string if no display-as - value is provided for the word, in which case the word is displayed as it is - spelled. + the word in a transcript. + * _For a custom model that is based on a previous-generation model_, the field + can contain an empty string if no display-as value is provided for a word that + exists in the service's base vocabulary. In this case, the word is displayed as + it is spelled. + * _For a custom model that is based on a next-generation model_, the service + uses the spelling of the word as the value of the display-as field when the word + is added to the model. :attr int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times in one corpus and seven @@ -8104,19 +8447,23 @@ def __init__(self, :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :param List[str] sounds_like: _For a custom model that is based on a - previous-generation model_, an array of as many as five pronunciations for - the word. The array can include the sounds-like pronunciation that is - automatically generated by the service if none is provided when the word is - added to the custom model; the service adds this pronunciation when it - finishes processing the word. - _For a custom model that is based on a next-generation model_, this field - does not apply. Custom models based on next-generation models do not - support the `sounds_like` field, which is ignored. + :param List[str] sounds_like: An array of as many as five pronunciations + for the word. + * _For a custom model that is based on a previous-generation model_, in + addition to sounds-like pronunciations that were added by a user, the array + can include a sounds-like pronunciation that is automatically generated by + the service if none is provided when the word is added to the custom model. + * _For a custom model that is based on a next-generation model_, the array + can include only sounds-like pronunciations that were added by a user. :param str display_as: The spelling of the word that the service uses to - display the word in a transcript. The field contains an empty string if no - display-as value is provided for the word, in which case the word is - displayed as it is spelled. + display the word in a transcript. + * _For a custom model that is based on a previous-generation model_, the + field can contain an empty string if no display-as value is provided for a + word that exists in the service's base vocabulary. In this case, the word + is displayed as it is spelled. + * _For a custom model that is based on a next-generation model_, the + service uses the spelling of the word as the value of the display-as field + when the word is added to the model. :param int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times @@ -8179,7 +8526,7 @@ def from_dict(cls, _dict: Dict) -> 'Word': raise ValueError( 'Required property \'source\' not present in Word JSON') if 'error' in _dict: - args['error'] = [WordError.from_dict(x) for x in _dict.get('error')] + args['error'] = [WordError.from_dict(v) for v in _dict.get('error')] return cls(**args) @classmethod @@ -8201,7 +8548,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'error') and self.error is not None: - _dict['error'] = [x.to_dict() for x in self.error] + error_list = [] + for v in self.error: + if isinstance(v, dict): + error_list.append(v) + else: + error_list.append(v.to_dict()) + _dict['error'] = error_list return _dict def _to_dict(self): @@ -8340,8 +8693,8 @@ def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': ) if 'alternatives' in _dict: args['alternatives'] = [ - WordAlternativeResult.from_dict(x) - for x in _dict.get('alternatives') + WordAlternativeResult.from_dict(v) + for v in _dict.get('alternatives') ] else: raise ValueError( @@ -8362,7 +8715,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'end_time') and self.end_time is not None: _dict['end_time'] = self.end_time if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list return _dict def _to_dict(self): @@ -8477,7 +8836,7 @@ def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + args['words'] = [Word.from_dict(v) for v in _dict.get('words')] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -8492,7 +8851,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list return _dict def _to_dict(self): diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index e9119ff72..5b0fa08d7 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -45,7 +45,6 @@ def recognize_using_websocket(self, speaker_labels=None, http_proxy_host=None, http_proxy_port=None, - customization_id=None, grammar_name=None, redaction=None, processing_metrics=None, @@ -56,6 +55,7 @@ def recognize_using_websocket(self, speech_detector_sensitivity=None, background_audio_suppression=None, low_latency=None, + character_insertion_bias=None, **kwargs): """ Sends audio for speech recognition using web sockets. @@ -190,10 +190,6 @@ def recognize_using_websocket(self, labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. - :param str customization_id: (optional) **Deprecated.** Use the - `language_customization_id` parameter to specify the customization ID - (GUID) of a custom language model that is to be used with the recognition - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -287,6 +283,28 @@ def recognize_using_websocket(self, for next-generation models. * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For next-generation + `Multimedia` and `Telephony` models, an indication of whether the service + is biased to recognize shorter or longer strings of characters when + developing transcription hypotheses. By default, the service is optimized + for each individual model to balance its recognition of strings of + different lengths. The model-specific bias is equivalent to 0.0. + The value that you specify represents a change from a model's default bias. + The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation `Broadband` and + `Narrowband` models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict @@ -321,7 +339,6 @@ def recognize_using_websocket(self, params = { 'model': model, - 'customization_id': customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id @@ -353,7 +370,8 @@ def recognize_using_websocket(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias } options = {k: v for k, v in options.items() if v is not None} request['options'] = options diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index c05763a08..0cd22fd74 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -30,6 +30,9 @@ def synthesize_using_websocket(self, voice=None, timings=None, customization_id=None, + spell_out_mode=None, + rate_percentage=None, + pitch_percentage=None, http_proxy_host=None, http_proxy_port=None, **kwargs): @@ -60,6 +63,51 @@ def synthesize_using_websocket(self, If you include a customization ID, you must call the method with the service credentials of the custom model's owner. Omit the parameter to use the specified voice with no customization. For more information, see [Understanding customization] (https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro). + :param str spell_out_mode: (optional) *For German voices,* indicates how + the service is to spell out strings of individual letters. To indicate the + pace of the spelling, specify one of the following values: + * `default` - The service reads the characters at the rate at which it + synthesizes speech for the request. You can also omit the parameter + entirely to achieve the default behavior. + * `singles` - The service reads the characters one at a time, with a brief + pause between each character. + * `pairs` - The service reads the characters two at a time, with a brief + pause between each pair. + * `triples` - The service reads the characters three at a time, with a + brief pause between each triplet. + The parameter is available only for IBM Cloud. + **See also:** [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + :param int rate_percentage: (optional) The percentage change from the + default speaking rate of the voice that is used for speech synthesis. Each + voice has a default speaking rate that is optimized to represent a normal + rate of speech. The parameter accepts an integer that represents the + percentage change from the voice's default rate: + * Specify a signed negative integer to reduce the speaking rate by that + percentage. For example, -10 reduces the rate by ten percent. + * Specify an unsigned or signed positive integer to increase the speaking + rate by that percentage. For example, 10 and +10 increase the rate by ten + percent. + * Specify 0 or omit the parameter to get the default speaking rate for the + voice. + The parameter affects the rate for an entire request. + For more information, see [Modifying the speaking + rate](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-rate-percentage). + :param int pitch_percentage: (optional) The percentage change from the + default speaking pitch of the voice that is used for speech synthesis. Each + voice has a default speaking pitch that is optimized to represent a normal + tone of voice. The parameter accepts an integer that represents the + percentage change from the voice's default tone: + * Specify a signed negative integer to lower the voice's pitch by that + percentage. For example, -5 reduces the tone by five percent. + * Specify an unsigned or signed positive integer to increase the voice's + pitch by that percentage. For example, 5 and +5 increase the tone by five + percent. + * Specify 0 or omit the parameter to get the default speaking pitch for the + voice. + The parameter affects the pitch for an entire request. + For more information, see [Modifying the speaking + pitch](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-pitch-percentage). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param dict headers: A `dict` containing the request headers @@ -90,6 +138,9 @@ def synthesize_using_websocket(self, params = { 'voice': voice, 'customization_id': customization_id, + 'spell_out_mode': spell_out_mode, + 'rate_percentage': rate_percentage, + 'pitch_percentage': pitch_percentage } params = {k: v for k, v in params.items() if v is not None} url += '/v1/synthesize?{0}'.format(urlencode(params)) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 9d5514257..f2cfe225f 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -35,6 +35,13 @@ The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service support custom prompts only for US English custom models and voices. +Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices +remain available to existing users until 31 March 2023, when they will be removed from the +service and the documentation. *No enhanced neural voices or expressive neural voices are +deprecated.*

For more information, see the [1 March 2023 service +update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) +in the release notes for {{site.data.keyword.texttospeechshort}} for +{{site.data.keyword.cloud_notm}}.{: deprecated} API Version: 1.0.0 See: https://cloud.ibm.com/docs/text-to-speech @@ -94,8 +101,15 @@ def list_voices(self, **kwargs) -> DetailedResponse: list of voices can change from call to call; do not rely on an alphabetized or static list of voices. To see information about a specific voice, use the [Get a voice](#getvoice). - **See also:** [Listing all available - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) + in the release notes. + **See also:** [Listing all + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-all-voices). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -110,6 +124,7 @@ def list_voices(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/voices' @@ -132,11 +147,14 @@ def get_voice(self, specified voice. To list information about all available voices, use the [List voices](#listvoices) method. **See also:** [Listing a specific - voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-specific-voice). + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) + in the release notes. :param str voice: The voice for which information is to be returned. :param str customization_id: (optional) The customization ID (GUID) of a @@ -149,7 +167,7 @@ def get_voice(self, :rtype: DetailedResponse with `dict` result representing a `Voice` object """ - if voice is None: + if not voice: raise ValueError('voice must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -157,10 +175,13 @@ def get_voice(self, operation_id='get_voice') headers.update(sdk_headers) - params = {'customization_id': customization_id} + params = { + 'customization_id': customization_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['voice'] @@ -185,6 +206,9 @@ def synthesize(self, accept: str = None, voice: str = None, customization_id: str = None, + spell_out_mode: str = None, + rate_percentage: int = None, + pitch_percentage: int = None, **kwargs) -> DetailedResponse: """ Synthesize audio. @@ -197,16 +221,19 @@ def synthesize(self, specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) + in the release notes. ### Audio formats (accept types) The service can return audio in the following formats (MIME types). * Where indicated, you can optionally specify the sampling rate (`rate`) of the - audio. You must specify a sampling rate for the `audio/l16` and `audio/mulaw` - formats. A specified sampling rate must lie in the range of 8 kHz to 192 kHz. Some - formats restrict the sampling rate to certain values, as noted. + audio. You must specify a sampling rate for the `audio/alaw`, `audio/l16`, and + `audio/mulaw` formats. A specified sampling rate must lie in the range of 8 kHz to + 192 kHz. Some formats restrict the sampling rate to certain values, as noted. * For the `audio/l16` format, you can optionally specify the endianness (`endianness`) of the audio: `endianness=big-endian` or `endianness=little-endian`. @@ -214,6 +241,7 @@ def synthesize(self, of the response audio. If you omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec (`audio/ogg;codecs=opus`). The service always returns single-channel audio. + * `audio/alaw` - You must specify the `rate` of the audio. * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz. * `audio/flac` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. @@ -244,6 +272,11 @@ def synthesize(self, For more information about specifying an audio format, including additional details about some of the formats, see [Using audio formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audio-formats). + **Note:** By default, the service returns audio in the Ogg audio format with the + Opus codec (`audio/ogg;codecs=opus`). However, the Ogg audio format is not + supported with the Safari browser. If you are using the service with the Safari + browser, you must use the `Accept` request header or the `accept` query parameter + specify a different format in which you want the service to return the audio. ### Warning messages If a request includes invalid query parameters, the service returns a `Warnings` response header that provides messages about the invalid parameters. The warning @@ -257,25 +290,67 @@ def synthesize(self, audio. You can use the `Accept` header or the `accept` parameter to specify the audio format. For more information about specifying an audio format, see **Audio formats (accept types)** in the method description. - :param str voice: (optional) The voice to use for synthesis. If you omit - the `voice` parameter, the service uses a default voice, which depends on - the version of the service that you are using: - * _For IBM Cloud,_ the service always uses the US English + :param str voice: (optional) The voice to use for speech synthesis. If you + omit the `voice` parameter, the service uses the US English `en-US_MichaelV3Voice` by default. - * _For IBM Cloud Pak for Data,_ the default voice depends on the voices - that you installed. If you installed the _enhanced neural voices_, the - service uses the US English `en-US_MichaelV3Voice` by default; if that - voice is not installed, you must specify a voice. If you installed the - _neural voices_, the service always uses the Australian English - `en-AU_MadisonVoice` by default. - **See also:** See also [Using languages and - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_MichaelV3Voice`, you must either specify a voice with the request or + specify a new default voice for your installation of the service. + **See also:** + * [Languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) + * [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str customization_id: (optional) The customization ID (GUID) of a custom model to use for the synthesis. If a custom model is specified, it works only if it matches the language of the indicated voice. You must make the request with credentials for the instance of the service that owns the custom model. Omit the parameter to use the specified voice with no customization. + :param str spell_out_mode: (optional) *For German voices,* indicates how + the service is to spell out strings of individual letters. To indicate the + pace of the spelling, specify one of the following values: + * `default` - The service reads the characters at the rate at which it + synthesizes speech for the request. You can also omit the parameter + entirely to achieve the default behavior. + * `singles` - The service reads the characters one at a time, with a brief + pause between each character. + * `pairs` - The service reads the characters two at a time, with a brief + pause between each pair. + * `triples` - The service reads the characters three at a time, with a + brief pause between each triplet. + For more information, see [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + :param int rate_percentage: (optional) The percentage change from the + default speaking rate of the voice that is used for speech synthesis. Each + voice has a default speaking rate that is optimized to represent a normal + rate of speech. The parameter accepts an integer that represents the + percentage change from the voice's default rate: + * Specify a signed negative integer to reduce the speaking rate by that + percentage. For example, -10 reduces the rate by ten percent. + * Specify an unsigned or signed positive integer to increase the speaking + rate by that percentage. For example, 10 and +10 increase the rate by ten + percent. + * Specify 0 or omit the parameter to get the default speaking rate for the + voice. + The parameter affects the rate for an entire request. + For more information, see [Modifying the speaking + rate](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-rate-percentage). + :param int pitch_percentage: (optional) The percentage change from the + default speaking pitch of the voice that is used for speech synthesis. Each + voice has a default speaking pitch that is optimized to represent a normal + tone of voice. The parameter accepts an integer that represents the + percentage change from the voice's default tone: + * Specify a signed negative integer to lower the voice's pitch by that + percentage. For example, -5 reduces the tone by five percent. + * Specify an unsigned or signed positive integer to increase the voice's + pitch by that percentage. For example, 5 and +5 increase the tone by five + percent. + * Specify 0 or omit the parameter to get the default speaking pitch for the + voice. + The parameter affects the pitch for an entire request. + For more information, see [Modifying the speaking + pitch](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-pitch-percentage). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `BinaryIO` result @@ -283,21 +358,32 @@ def synthesize(self, if text is None: raise ValueError('text must be provided') - headers = {'Accept': accept} + headers = { + 'Accept': accept, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='synthesize') headers.update(sdk_headers) - params = {'voice': voice, 'customization_id': customization_id} + params = { + 'voice': voice, + 'customization_id': customization_id, + 'spell_out_mode': spell_out_mode, + 'rate_percentage': rate_percentage, + 'pitch_percentage': pitch_percentage, + } - data = {'text': text} + data = { + 'text': text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/synthesize' request = self.prepare_request(method='POST', @@ -327,17 +413,26 @@ def get_pronunciation(self, pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom model to see the translation for that model. + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) + in the release notes. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. :param str text: The word for which the pronunciation is requested. :param str voice: (optional) A voice that specifies the language in which - the pronunciation is to be returned. All voices for the same language (for - example, `en-US`) return the same translation. + the pronunciation is to be returned. If you omit the `voice` parameter, the + service uses the US English `en-US_MichaelV3Voice` by default. All voices + for the same language (for example, `en-US`) return the same translation. + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_MichaelV3Voice`, you must either specify a voice with the request or + specify a new default voice for your installation of the service. + **See also:** [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str format: (optional) The phoneme format in which to return the pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. Omit the parameter to obtain the pronunciation @@ -355,7 +450,7 @@ def get_pronunciation(self, :rtype: DetailedResponse with `dict` result representing a `Pronunciation` object """ - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -367,11 +462,12 @@ def get_pronunciation(self, 'text': text, 'voice': voice, 'format': format, - 'customization_id': customization_id + 'customization_id': customization_id, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/pronunciation' @@ -402,24 +498,28 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR` language - identifier cannot be used to create a custom model; use the `ar-MS` identifier - instead. - - :param str name: The name of the new custom model. + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) + in the release notes. + + :param str name: The name of the new custom model. Use a localized name + that matches the language of the custom model. Use a name that describes + the purpose of the custom model, such as `Medical custom model` or `Legal + custom model`. Use a name that is unique among all custom models that you + own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str language: (optional) The language of the new custom model. You create a custom model for a specific language, not for a specific voice. A custom model can be used with any voice for its specified language. Omit the parameter to use the the default language, `en-US`. - **Important:** If you are using the service on IBM Cloud Pak for Data _and_ - you install the neural voices, the `language`parameter is required. You - must specify the language for the custom model in the indicated format (for - example, `en-AU` for Australian English). The request fails if you do not - specify a language. - :param str description: (optional) A description of the new custom model. - Specifying a description is recommended. + :param str description: (optional) A recommended description of the new + custom model. Use a localized description that matches the language of the + custom model. Include a maximum of 128 characters in the description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `CustomModel` object @@ -433,13 +533,18 @@ def create_custom_model(self, operation_id='create_custom_model') headers.update(sdk_headers) - data = {'name': name, 'language': language, 'description': description} + data = { + 'name': name, + 'language': language, + 'description': description, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -481,10 +586,13 @@ def list_custom_models(self, operation_id='list_custom_models') headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -543,7 +651,7 @@ def update_custom_model(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is not None: words = [convert_model(x) for x in words] @@ -553,13 +661,18 @@ def update_custom_model(self, operation_id='update_custom_model') headers.update(sdk_headers) - data = {'name': name, 'description': description, 'words': words} + data = { + 'name': name, + 'description': description, + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -595,7 +708,7 @@ def get_custom_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `CustomModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -605,6 +718,7 @@ def get_custom_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -634,7 +748,7 @@ def delete_custom_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -644,6 +758,7 @@ def delete_custom_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id'] path_param_values = self.encode_path_vars(customization_id) @@ -704,7 +819,7 @@ def add_words(self, customization_id: str, words: List['Word'], :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') @@ -715,13 +830,16 @@ def add_words(self, customization_id: str, words: List['Word'], operation_id='add_words') headers.update(sdk_headers) - data = {'words': words} + data = { + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -755,7 +873,7 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `Words` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -765,6 +883,7 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -833,9 +952,9 @@ def add_word(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') if translation is None: raise ValueError('translation must be provided') @@ -845,13 +964,17 @@ def add_word(self, operation_id='add_word') headers.update(sdk_headers) - data = {'translation': translation, 'part_of_speech': part_of_speech} + data = { + 'translation': translation, + 'part_of_speech': part_of_speech, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'word'] path_param_values = self.encode_path_vars(customization_id, word) @@ -886,9 +1009,9 @@ def get_word(self, customization_id: str, word: str, :rtype: DetailedResponse with `dict` result representing a `Translation` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -898,6 +1021,7 @@ def get_word(self, customization_id: str, word: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word'] @@ -929,9 +1053,9 @@ def delete_word(self, customization_id: str, word: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -941,6 +1065,7 @@ def delete_word(self, customization_id: str, word: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'word'] path_param_values = self.encode_path_vars(customization_id, word) @@ -983,7 +1108,7 @@ def list_custom_prompts(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompts` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -993,6 +1118,7 @@ def list_custom_prompts(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1110,9 +1236,9 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompt` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') if metadata is None: raise ValueError('metadata must be provided') @@ -1131,6 +1257,7 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'prompt_id'] @@ -1168,9 +1295,9 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompt` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1180,6 +1307,7 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'prompt_id'] @@ -1217,9 +1345,9 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1229,6 +1357,7 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'prompt_id'] path_param_values = self.encode_path_vars(customization_id, prompt_id) @@ -1271,6 +1400,7 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/speakers' @@ -1345,7 +1475,7 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, :rtype: DetailedResponse with `dict` result representing a `SpeakerModel` object """ - if speaker_name is None: + if not speaker_name: raise ValueError('speaker_name must be provided') if audio is None: raise ValueError('audio must be provided') @@ -1355,13 +1485,16 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, operation_id='create_speaker_model') headers.update(sdk_headers) - params = {'speaker_name': speaker_name} + params = { + 'speaker_name': speaker_name, + } data = audio headers['content-type'] = 'audio/wav' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/speakers' @@ -1397,7 +1530,7 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `SpeakerCustomModels` object """ - if speaker_id is None: + if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1407,6 +1540,7 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['speaker_id'] @@ -1444,7 +1578,7 @@ def delete_speaker_model(self, speaker_id: str, :rtype: DetailedResponse """ - if speaker_id is None: + if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1454,6 +1588,7 @@ def delete_speaker_model(self, speaker_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['speaker_id'] path_param_values = self.encode_path_vars(speaker_id) @@ -1495,7 +1630,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1503,10 +1638,13 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'customer_id': customer_id} + params = { + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' request = self.prepare_request(method='DELETE', @@ -1527,48 +1665,41 @@ class Voice(str, Enum): """ The voice for which information is to be returned. """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' @@ -1576,7 +1707,6 @@ class Voice(str, Enum): NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' @@ -1596,6 +1726,7 @@ class Accept(str, Enum): specifying an audio format, see **Audio formats (accept types)** in the method description. """ + AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' AUDIO_L16 = 'audio/l16' @@ -1612,61 +1743,52 @@ class Accept(str, Enum): class Voice(str, Enum): """ - The voice to use for synthesis. If you omit the `voice` parameter, the service - uses a default voice, which depends on the version of the service that you are - using: - * _For IBM Cloud,_ the service always uses the US English `en-US_MichaelV3Voice` - by default. - * _For IBM Cloud Pak for Data,_ the default voice depends on the voices that you - installed. If you installed the _enhanced neural voices_, the service uses the US - English `en-US_MichaelV3Voice` by default; if that voice is not installed, you - must specify a voice. If you installed the _neural voices_, the service always - uses the Australian English `en-AU_MadisonVoice` by default. - **See also:** See also [Using languages and - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). - """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' + The voice to use for speech synthesis. If you omit the `voice` parameter, the + service uses the US English `en-US_MichaelV3Voice` by default. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, + you must either specify a voice with the request or specify a new default voice + for your installation of the service. + **See also:** + * [Languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) + * [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). + """ AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' @@ -1674,13 +1796,34 @@ class Voice(str, Enum): NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' + class SpellOutMode(str, Enum): + """ + *For German voices,* indicates how the service is to spell out strings of + individual letters. To indicate the pace of the spelling, specify one of the + following values: + * `default` - The service reads the characters at the rate at which it synthesizes + speech for the request. You can also omit the parameter entirely to achieve the + default behavior. + * `singles` - The service reads the characters one at a time, with a brief pause + between each character. + * `pairs` - The service reads the characters two at a time, with a brief pause + between each pair. + * `triples` - The service reads the characters three at a time, with a brief pause + between each triplet. + For more information, see [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + """ + DEFAULT = 'default' + SINGLES = 'singles' + PAIRS = 'pairs' + TRIPLES = 'triples' + class GetPronunciationEnums: """ @@ -1690,51 +1833,50 @@ class GetPronunciationEnums: class Voice(str, Enum): """ A voice that specifies the language in which the pronunciation is to be returned. - All voices for the same language (for example, `en-US`) return the same - translation. + If you omit the `voice` parameter, the service uses the US English + `en-US_MichaelV3Voice` by default. All voices for the same language (for example, + `en-US`) return the same translation. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, + you must either specify a voice with the request or specify a new default voice + for your installation of the service. + **See also:** [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' @@ -1742,7 +1884,6 @@ class Voice(str, Enum): NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' @@ -1904,10 +2045,10 @@ def from_dict(cls, _dict: Dict) -> 'CustomModel': if 'description' in _dict: args['description'] = _dict.get('description') if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + args['words'] = [Word.from_dict(v) for v in _dict.get('words')] if 'prompts' in _dict: args['prompts'] = [ - Prompt.from_dict(x) for x in _dict.get('prompts') + Prompt.from_dict(v) for v in _dict.get('prompts') ] return cls(**args) @@ -1935,9 +2076,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -1986,7 +2139,7 @@ def from_dict(cls, _dict: Dict) -> 'CustomModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - CustomModel.from_dict(x) for x in _dict.get('customizations') + CustomModel.from_dict(v) for v in _dict.get('customizations') ] else: raise ValueError( @@ -2003,7 +2156,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -2248,7 +2407,7 @@ def from_dict(cls, _dict: Dict) -> 'Prompts': args = {} if 'prompts' in _dict: args['prompts'] = [ - Prompt.from_dict(x) for x in _dict.get('prompts') + Prompt.from_dict(v) for v in _dict.get('prompts') ] else: raise ValueError( @@ -2264,7 +2423,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -2452,7 +2617,7 @@ def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModel': ) if 'prompts' in _dict: args['prompts'] = [ - SpeakerPrompt.from_dict(x) for x in _dict.get('prompts') + SpeakerPrompt.from_dict(v) for v in _dict.get('prompts') ] else: raise ValueError( @@ -2472,7 +2637,13 @@ def to_dict(self) -> Dict: 'customization_id') and self.customization_id is not None: _dict['customization_id'] = self.customization_id if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -2522,8 +2693,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - SpeakerCustomModel.from_dict(x) - for x in _dict.get('customizations') + SpeakerCustomModel.from_dict(v) + for v in _dict.get('customizations') ] else: raise ValueError( @@ -2540,7 +2711,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -2754,7 +2931,7 @@ def from_dict(cls, _dict: Dict) -> 'Speakers': args = {} if 'speakers' in _dict: args['speakers'] = [ - Speaker.from_dict(x) for x in _dict.get('speakers') + Speaker.from_dict(v) for v in _dict.get('speakers') ] else: raise ValueError( @@ -2770,7 +2947,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'speakers') and self.speakers is not None: - _dict['speakers'] = [x.to_dict() for x in self.speakers] + speakers_list = [] + for v in self.speakers: + if isinstance(v, dict): + speakers_list.append(v) + else: + speakers_list.append(v.to_dict()) + _dict['speakers'] = speakers_list return _dict def _to_dict(self): @@ -3115,9 +3298,15 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features.to_dict() + if isinstance(self.supported_features, dict): + _dict['supported_features'] = self.supported_features + else: + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'customization') and self.customization is not None: - _dict['customization'] = self.customization.to_dict() + if isinstance(self.customization, dict): + _dict['customization'] = self.customization + else: + _dict['customization'] = self.customization.to_dict() return _dict def _to_dict(self): @@ -3159,7 +3348,7 @@ def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} if 'voices' in _dict: - args['voices'] = [Voice.from_dict(x) for x in _dict.get('voices')] + args['voices'] = [Voice.from_dict(v) for v in _dict.get('voices')] else: raise ValueError( 'Required property \'voices\' not present in Voices JSON') @@ -3174,7 +3363,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'voices') and self.voices is not None: - _dict['voices'] = [x.to_dict() for x in self.voices] + voices_list = [] + for v in self.voices: + if isinstance(v, dict): + voices_list.append(v) + else: + voices_list.append(v.to_dict()) + _dict['voices'] = voices_list return _dict def _to_dict(self): @@ -3361,7 +3556,7 @@ def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + args['words'] = [Word.from_dict(v) for v in _dict.get('words')] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -3376,7 +3571,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list return _dict def _to_dict(self): diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 1d4672ff0..5220ac1a6 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.3.0' +__version__ = '7.0.0' diff --git a/setup.py b/setup.py index 09a62b2a8..0dafd3d02 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '5.3.0' +__version__ = '7.0.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 696a08a7b..86aa0933f 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ _service = AssistantV1( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' @@ -83,7 +83,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -164,7 +164,7 @@ def test_message_all_params(self): # Construct a dict representation of a Context model context_model = {} context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -186,28 +186,14 @@ def test_message_all_params(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - # Construct a dict representation of a DialogNodeOutputOptionsElementValue model - dialog_node_output_options_element_value_model = {} - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - # Construct a dict representation of a DialogNodeOutputOptionsElement model - dialog_node_output_options_element_model = {} - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeOption model + # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeText model runtime_response_generic_model = {} - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a OutputData model @@ -276,7 +262,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -312,7 +298,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -331,7 +317,6 @@ def test_message_value_error(self): with pytest.raises(ValueError): _service.message(**req_copy) - def test_message_value_error_with_retries(self): # Enable retries and run test_message_value_error. _service.enable_retries() @@ -463,7 +448,6 @@ def test_bulk_classify_value_error(self): with pytest.raises(ValueError): _service.bulk_classify(**req_copy) - def test_bulk_classify_value_error_with_retries(self): # Enable retries and run test_bulk_classify_value_error. _service.enable_retries() @@ -495,7 +479,7 @@ def test_list_workspaces_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -547,7 +531,7 @@ def test_list_workspaces_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -578,7 +562,7 @@ def test_list_workspaces_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -593,7 +577,6 @@ def test_list_workspaces_value_error(self): with pytest.raises(ValueError): _service.list_workspaces(**req_copy) - def test_list_workspaces_value_error_with_retries(self): # Enable retries and run test_list_workspaces_value_error. _service.enable_retries() @@ -615,26 +598,28 @@ def test_create_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -643,13 +628,13 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -662,7 +647,7 @@ def test_create_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -675,7 +660,7 @@ def test_create_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -714,15 +699,20 @@ def test_create_workspace_all_params(self): workspace_system_settings_off_topic_model = {} workspace_system_settings_off_topic_model['enabled'] = False + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model @@ -755,7 +745,7 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -764,7 +754,7 @@ def test_create_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {} + create_entity_model['metadata'] = {'foo': 'bar'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -774,7 +764,7 @@ def test_create_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {} + metadata = {'foo': 'bar'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -813,7 +803,7 @@ def test_create_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -836,7 +826,7 @@ def test_create_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -867,7 +857,7 @@ def test_create_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -882,7 +872,6 @@ def test_create_workspace_value_error(self): with pytest.raises(ValueError): _service.create_workspace(**req_copy) - def test_create_workspace_value_error_with_retries(self): # Enable retries and run test_create_workspace_value_error. _service.enable_retries() @@ -904,7 +893,7 @@ def test_get_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -952,7 +941,7 @@ def test_get_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -988,7 +977,7 @@ def test_get_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -1007,7 +996,6 @@ def test_get_workspace_value_error(self): with pytest.raises(ValueError): _service.get_workspace(**req_copy) - def test_get_workspace_value_error_with_retries(self): # Enable retries and run test_get_workspace_value_error. _service.enable_retries() @@ -1029,26 +1017,28 @@ def test_update_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -1057,13 +1047,13 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1076,7 +1066,7 @@ def test_update_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1089,7 +1079,7 @@ def test_update_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1128,15 +1118,20 @@ def test_update_workspace_all_params(self): workspace_system_settings_off_topic_model = {} workspace_system_settings_off_topic_model['enabled'] = False + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model @@ -1169,7 +1164,7 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1178,7 +1173,7 @@ def test_update_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {} + create_entity_model['metadata'] = {'foo': 'bar'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1189,7 +1184,7 @@ def test_update_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {} + metadata = {'foo': 'bar'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1232,7 +1227,7 @@ def test_update_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1255,7 +1250,7 @@ def test_update_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1291,7 +1286,7 @@ def test_update_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1310,7 +1305,6 @@ def test_update_workspace_value_error(self): with pytest.raises(ValueError): _service.update_workspace(**req_copy) - def test_update_workspace_value_error_with_retries(self): # Enable retries and run test_update_workspace_value_error. _service.enable_retries() @@ -1340,7 +1334,723 @@ def test_delete_workspace_all_params(self): workspace_id = 'testString' # Invoke method - response = _service.delete_workspace( + response = _service.delete_workspace( + workspace_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_workspace_all_params_with_retries(self): + # Enable retries and run test_delete_workspace_all_params. + _service.enable_retries() + self.test_delete_workspace_all_params() + + # Disable retries and run test_delete_workspace_all_params. + _service.disable_retries() + self.test_delete_workspace_all_params() + + @responses.activate + def test_delete_workspace_value_error(self): + """ + test_delete_workspace_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_workspace(**req_copy) + + def test_delete_workspace_value_error_with_retries(self): + # Enable retries and run test_delete_workspace_value_error. + _service.enable_retries() + self.test_delete_workspace_value_error() + + # Disable retries and run test_delete_workspace_value_error. + _service.disable_retries() + self.test_delete_workspace_value_error() + +class TestCreateWorkspaceAsync(): + """ + Test Class for create_workspace_async + """ + + @responses.activate + def test_create_workspace_async_all_params(self): + """ + create_workspace_async() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = False + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = False + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model + workspace_system_settings_model['foo'] = 'testString' + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {'foo': 'bar'} + learning_opt_out = False + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + + # Invoke method + response = _service.create_workspace_async( + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['learning_opt_out'] == False + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + def test_create_workspace_async_all_params_with_retries(self): + # Enable retries and run test_create_workspace_async_all_params. + _service.enable_retries() + self.test_create_workspace_async_all_params() + + # Disable retries and run test_create_workspace_async_all_params. + _service.disable_retries() + self.test_create_workspace_async_all_params() + + @responses.activate + def test_create_workspace_async_required_params(self): + """ + test_create_workspace_async_required_params() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Invoke method + response = _service.create_workspace_async() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_create_workspace_async_required_params_with_retries(self): + # Enable retries and run test_create_workspace_async_required_params. + _service.enable_retries() + self.test_create_workspace_async_required_params() + + # Disable retries and run test_create_workspace_async_required_params. + _service.disable_retries() + self.test_create_workspace_async_required_params() + + @responses.activate + def test_create_workspace_async_value_error(self): + """ + test_create_workspace_async_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_workspace_async(**req_copy) + + def test_create_workspace_async_value_error_with_retries(self): + # Enable retries and run test_create_workspace_async_value_error. + _service.enable_retries() + self.test_create_workspace_async_value_error() + + # Disable retries and run test_create_workspace_async_value_error. + _service.disable_retries() + self.test_create_workspace_async_value_error() + +class TestUpdateWorkspaceAsync(): + """ + Test Class for update_workspace_async + """ + + @responses.activate + def test_update_workspace_async_all_params(self): + """ + update_workspace_async() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = False + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = False + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model + workspace_system_settings_model['foo'] = 'testString' + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + workspace_id = 'testString' + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {'foo': 'bar'} + learning_opt_out = False + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + append = False + + # Invoke method + response = _service.update_workspace_async( + workspace_id, + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + append=append, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'append={}'.format('true' if append else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['learning_opt_out'] == False + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + def test_update_workspace_async_all_params_with_retries(self): + # Enable retries and run test_update_workspace_async_all_params. + _service.enable_retries() + self.test_update_workspace_async_all_params() + + # Disable retries and run test_update_workspace_async_all_params. + _service.disable_retries() + self.test_update_workspace_async_all_params() + + @responses.activate + def test_update_workspace_async_required_params(self): + """ + test_update_workspace_async_required_params() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.update_workspace_async( + workspace_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_update_workspace_async_required_params_with_retries(self): + # Enable retries and run test_update_workspace_async_required_params. + _service.enable_retries() + self.test_update_workspace_async_required_params() + + # Disable retries and run test_update_workspace_async_required_params. + _service.disable_retries() + self.test_update_workspace_async_required_params() + + @responses.activate + def test_update_workspace_async_value_error(self): + """ + test_update_workspace_async_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_workspace_async(**req_copy) + + def test_update_workspace_async_value_error_with_retries(self): + # Enable retries and run test_update_workspace_async_value_error. + _service.enable_retries() + self.test_update_workspace_async_value_error() + + # Disable retries and run test_update_workspace_async_value_error. + _service.disable_retries() + self.test_update_workspace_async_value_error() + +class TestExportWorkspaceAsync(): + """ + Test Class for export_workspace_async + """ + + @responses.activate + def test_export_workspace_async_all_params(self): + """ + export_workspace_async() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + include_audit = False + sort = 'stable' + verbose = False + + # Invoke method + response = _service.export_workspace_async( + workspace_id, + include_audit=include_audit, + sort=sort, + verbose=verbose, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'verbose={}'.format('true' if verbose else 'false') in query_string + + def test_export_workspace_async_all_params_with_retries(self): + # Enable retries and run test_export_workspace_async_all_params. + _service.enable_retries() + self.test_export_workspace_async_all_params() + + # Disable retries and run test_export_workspace_async_all_params. + _service.disable_retries() + self.test_export_workspace_async_all_params() + + @responses.activate + def test_export_workspace_async_required_params(self): + """ + test_export_workspace_async_required_params() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.export_workspace_async( workspace_id, headers={} ) @@ -1349,24 +2059,27 @@ def test_delete_workspace_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_delete_workspace_all_params_with_retries(self): - # Enable retries and run test_delete_workspace_all_params. + def test_export_workspace_async_required_params_with_retries(self): + # Enable retries and run test_export_workspace_async_required_params. _service.enable_retries() - self.test_delete_workspace_all_params() + self.test_export_workspace_async_required_params() - # Disable retries and run test_delete_workspace_all_params. + # Disable retries and run test_export_workspace_async_required_params. _service.disable_retries() - self.test_delete_workspace_all_params() + self.test_export_workspace_async_required_params() @responses.activate - def test_delete_workspace_value_error(self): + def test_export_workspace_async_value_error(self): """ - test_delete_workspace_value_error() + test_export_workspace_async_value_error() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, url, + body=mock_response, + content_type='application/json', status=200) # Set up parameter values @@ -1379,17 +2092,16 @@ def test_delete_workspace_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_workspace(**req_copy) + _service.export_workspace_async(**req_copy) - - def test_delete_workspace_value_error_with_retries(self): - # Enable retries and run test_delete_workspace_value_error. + def test_export_workspace_async_value_error_with_retries(self): + # Enable retries and run test_export_workspace_async_value_error. _service.enable_retries() - self.test_delete_workspace_value_error() + self.test_export_workspace_async_value_error() - # Disable retries and run test_delete_workspace_value_error. + # Disable retries and run test_export_workspace_async_value_error. _service.disable_retries() - self.test_delete_workspace_value_error() + self.test_export_workspace_async_value_error() # endregion ############################################################################## @@ -1525,7 +2237,6 @@ def test_list_intents_value_error(self): with pytest.raises(ValueError): _service.list_intents(**req_copy) - def test_list_intents_value_error_with_retries(self): # Enable retries and run test_list_intents_value_error. _service.enable_retries() @@ -1700,7 +2411,6 @@ def test_create_intent_value_error(self): with pytest.raises(ValueError): _service.create_intent(**req_copy) - def test_create_intent_value_error_with_retries(self): # Enable retries and run test_create_intent_value_error. _service.enable_retries() @@ -1828,7 +2538,6 @@ def test_get_intent_value_error(self): with pytest.raises(ValueError): _service.get_intent(**req_copy) - def test_get_intent_value_error_with_retries(self): # Enable retries and run test_get_intent_value_error. _service.enable_retries() @@ -2011,7 +2720,6 @@ def test_update_intent_value_error(self): with pytest.raises(ValueError): _service.update_intent(**req_copy) - def test_update_intent_value_error_with_retries(self): # Enable retries and run test_update_intent_value_error. _service.enable_retries() @@ -2086,7 +2794,6 @@ def test_delete_intent_value_error(self): with pytest.raises(ValueError): _service.delete_intent(**req_copy) - def test_delete_intent_value_error_with_retries(self): # Enable retries and run test_delete_intent_value_error. _service.enable_retries() @@ -2233,7 +2940,6 @@ def test_list_examples_value_error(self): with pytest.raises(ValueError): _service.list_examples(**req_copy) - def test_list_examples_value_error_with_retries(self): # Enable retries and run test_list_examples_value_error. _service.enable_retries() @@ -2392,7 +3098,6 @@ def test_create_example_value_error(self): with pytest.raises(ValueError): _service.create_example(**req_copy) - def test_create_example_value_error_with_retries(self): # Enable retries and run test_create_example_value_error. _service.enable_retries() @@ -2523,7 +3228,6 @@ def test_get_example_value_error(self): with pytest.raises(ValueError): _service.get_example(**req_copy) - def test_get_example_value_error_with_retries(self): # Enable retries and run test_get_example_value_error. _service.enable_retries() @@ -2687,7 +3391,6 @@ def test_update_example_value_error(self): with pytest.raises(ValueError): _service.update_example(**req_copy) - def test_update_example_value_error_with_retries(self): # Enable retries and run test_update_example_value_error. _service.enable_retries() @@ -2766,7 +3469,6 @@ def test_delete_example_value_error(self): with pytest.raises(ValueError): _service.delete_example(**req_copy) - def test_delete_example_value_error_with_retries(self): # Enable retries and run test_delete_example_value_error. _service.enable_retries() @@ -2907,7 +3609,6 @@ def test_list_counterexamples_value_error(self): with pytest.raises(ValueError): _service.list_counterexamples(**req_copy) - def test_list_counterexamples_value_error_with_retries(self): # Enable retries and run test_list_counterexamples_value_error. _service.enable_retries() @@ -3038,7 +3739,6 @@ def test_create_counterexample_value_error(self): with pytest.raises(ValueError): _service.create_counterexample(**req_copy) - def test_create_counterexample_value_error_with_retries(self): # Enable retries and run test_create_counterexample_value_error. _service.enable_retries() @@ -3163,7 +3863,6 @@ def test_get_counterexample_value_error(self): with pytest.raises(ValueError): _service.get_counterexample(**req_copy) - def test_get_counterexample_value_error_with_retries(self): # Enable retries and run test_get_counterexample_value_error. _service.enable_retries() @@ -3299,7 +3998,6 @@ def test_update_counterexample_value_error(self): with pytest.raises(ValueError): _service.update_counterexample(**req_copy) - def test_update_counterexample_value_error_with_retries(self): # Enable retries and run test_update_counterexample_value_error. _service.enable_retries() @@ -3374,7 +4072,6 @@ def test_delete_counterexample_value_error(self): with pytest.raises(ValueError): _service.delete_counterexample(**req_copy) - def test_delete_counterexample_value_error_with_retries(self): # Enable retries and run test_delete_counterexample_value_error. _service.enable_retries() @@ -3406,7 +4103,7 @@ def test_list_entities_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3463,7 +4160,7 @@ def test_list_entities_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3499,7 +4196,7 @@ def test_list_entities_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3518,7 +4215,6 @@ def test_list_entities_value_error(self): with pytest.raises(ValueError): _service.list_entities(**req_copy) - def test_list_entities_value_error_with_retries(self): # Enable retries and run test_list_entities_value_error. _service.enable_retries() @@ -3540,7 +4236,7 @@ def test_create_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3550,7 +4246,7 @@ def test_create_entity_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3559,7 +4255,7 @@ def test_create_entity_all_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'foo': 'bar'} fuzzy_match = True values = [create_value_model] include_audit = False @@ -3587,7 +4283,7 @@ def test_create_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3607,7 +4303,7 @@ def test_create_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3617,7 +4313,7 @@ def test_create_entity_required_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3626,7 +4322,7 @@ def test_create_entity_required_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'foo': 'bar'} fuzzy_match = True values = [create_value_model] @@ -3648,7 +4344,7 @@ def test_create_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3668,7 +4364,7 @@ def test_create_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3678,7 +4374,7 @@ def test_create_entity_value_error(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3687,7 +4383,7 @@ def test_create_entity_value_error(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'foo': 'bar'} fuzzy_match = True values = [create_value_model] @@ -3701,7 +4397,6 @@ def test_create_entity_value_error(self): with pytest.raises(ValueError): _service.create_entity(**req_copy) - def test_create_entity_value_error_with_retries(self): # Enable retries and run test_create_entity_value_error. _service.enable_retries() @@ -3723,7 +4418,7 @@ def test_get_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3770,7 +4465,7 @@ def test_get_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3808,7 +4503,7 @@ def test_get_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3829,7 +4524,6 @@ def test_get_entity_value_error(self): with pytest.raises(ValueError): _service.get_entity(**req_copy) - def test_get_entity_value_error_with_retries(self): # Enable retries and run test_get_entity_value_error. _service.enable_retries() @@ -3851,7 +4545,7 @@ def test_update_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3861,7 +4555,7 @@ def test_update_entity_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3871,7 +4565,7 @@ def test_update_entity_all_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'foo': 'bar'} new_fuzzy_match = True new_values = [create_value_model] append = False @@ -3903,7 +4597,7 @@ def test_update_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3923,7 +4617,7 @@ def test_update_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3933,7 +4627,7 @@ def test_update_entity_required_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3943,7 +4637,7 @@ def test_update_entity_required_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'foo': 'bar'} new_fuzzy_match = True new_values = [create_value_model] @@ -3966,7 +4660,7 @@ def test_update_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3986,7 +4680,7 @@ def test_update_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3996,7 +4690,7 @@ def test_update_entity_value_error(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4006,7 +4700,7 @@ def test_update_entity_value_error(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'foo': 'bar'} new_fuzzy_match = True new_values = [create_value_model] @@ -4020,7 +4714,6 @@ def test_update_entity_value_error(self): with pytest.raises(ValueError): _service.update_entity(**req_copy) - def test_update_entity_value_error_with_retries(self): # Enable retries and run test_update_entity_value_error. _service.enable_retries() @@ -4095,7 +4788,6 @@ def test_delete_entity_value_error(self): with pytest.raises(ValueError): _service.delete_entity(**req_copy) - def test_delete_entity_value_error_with_retries(self): # Enable retries and run test_delete_entity_value_error. _service.enable_retries() @@ -4233,7 +4925,6 @@ def test_list_mentions_value_error(self): with pytest.raises(ValueError): _service.list_mentions(**req_copy) - def test_list_mentions_value_error_with_retries(self): # Enable retries and run test_list_mentions_value_error. _service.enable_retries() @@ -4265,7 +4956,7 @@ def test_list_values_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4324,7 +5015,7 @@ def test_list_values_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4362,7 +5053,7 @@ def test_list_values_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4383,7 +5074,6 @@ def test_list_values_value_error(self): with pytest.raises(ValueError): _service.list_values(**req_copy) - def test_list_values_value_error_with_retries(self): # Enable retries and run test_list_values_value_error. _service.enable_retries() @@ -4405,7 +5095,7 @@ def test_create_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4416,7 +5106,7 @@ def test_create_value_all_params(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'foo': 'bar'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4445,7 +5135,7 @@ def test_create_value_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4466,7 +5156,7 @@ def test_create_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4477,7 +5167,7 @@ def test_create_value_required_params(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'foo': 'bar'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4500,7 +5190,7 @@ def test_create_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4521,7 +5211,7 @@ def test_create_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4532,7 +5222,7 @@ def test_create_value_value_error(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'foo': 'bar'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4548,7 +5238,6 @@ def test_create_value_value_error(self): with pytest.raises(ValueError): _service.create_value(**req_copy) - def test_create_value_value_error_with_retries(self): # Enable retries and run test_create_value_value_error. _service.enable_retries() @@ -4570,7 +5259,7 @@ def test_get_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4619,7 +5308,7 @@ def test_get_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4659,7 +5348,7 @@ def test_get_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4682,7 +5371,6 @@ def test_get_value_value_error(self): with pytest.raises(ValueError): _service.get_value(**req_copy) - def test_get_value_value_error_with_retries(self): # Enable retries and run test_get_value_value_error. _service.enable_retries() @@ -4704,7 +5392,7 @@ def test_update_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4716,7 +5404,7 @@ def test_update_value_all_params(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'foo': 'bar'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4749,7 +5437,7 @@ def test_update_value_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4770,7 +5458,7 @@ def test_update_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4782,7 +5470,7 @@ def test_update_value_required_params(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'foo': 'bar'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4806,7 +5494,7 @@ def test_update_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4827,7 +5515,7 @@ def test_update_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4839,7 +5527,7 @@ def test_update_value_value_error(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'foo': 'bar'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4855,7 +5543,6 @@ def test_update_value_value_error(self): with pytest.raises(ValueError): _service.update_value(**req_copy) - def test_update_value_value_error_with_retries(self): # Enable retries and run test_update_value_value_error. _service.enable_retries() @@ -4934,7 +5621,6 @@ def test_delete_value_value_error(self): with pytest.raises(ValueError): _service.delete_value(**req_copy) - def test_delete_value_value_error_with_retries(self): # Enable retries and run test_delete_value_value_error. _service.enable_retries() @@ -5087,7 +5773,6 @@ def test_list_synonyms_value_error(self): with pytest.raises(ValueError): _service.list_synonyms(**req_copy) - def test_list_synonyms_value_error_with_retries(self): # Enable retries and run test_list_synonyms_value_error. _service.enable_retries() @@ -5230,7 +5915,6 @@ def test_create_synonym_value_error(self): with pytest.raises(ValueError): _service.create_synonym(**req_copy) - def test_create_synonym_value_error_with_retries(self): # Enable retries and run test_create_synonym_value_error. _service.enable_retries() @@ -5367,7 +6051,6 @@ def test_get_synonym_value_error(self): with pytest.raises(ValueError): _service.get_synonym(**req_copy) - def test_get_synonym_value_error_with_retries(self): # Enable retries and run test_get_synonym_value_error. _service.enable_retries() @@ -5515,7 +6198,6 @@ def test_update_synonym_value_error(self): with pytest.raises(ValueError): _service.update_synonym(**req_copy) - def test_update_synonym_value_error_with_retries(self): # Enable retries and run test_update_synonym_value_error. _service.enable_retries() @@ -5598,7 +6280,6 @@ def test_delete_synonym_value_error(self): with pytest.raises(ValueError): _service.delete_synonym(**req_copy) - def test_delete_synonym_value_error_with_retries(self): # Enable retries and run test_delete_synonym_value_error. _service.enable_retries() @@ -5630,7 +6311,7 @@ def test_list_dialog_nodes_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5684,7 +6365,7 @@ def test_list_dialog_nodes_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5720,7 +6401,7 @@ def test_list_dialog_nodes_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5739,7 +6420,6 @@ def test_list_dialog_nodes_value_error(self): with pytest.raises(ValueError): _service.list_dialog_nodes(**req_copy) - def test_list_dialog_nodes_value_error_with_retries(self): # Enable retries and run test_list_dialog_nodes_value_error. _service.enable_retries() @@ -5761,26 +6441,28 @@ def test_create_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5789,13 +6471,13 @@ def test_create_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -5808,7 +6490,7 @@ def test_create_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -5821,7 +6503,7 @@ def test_create_dialog_node_all_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'foo': 'bar'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -5877,7 +6559,7 @@ def test_create_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -5906,26 +6588,28 @@ def test_create_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5934,13 +6618,13 @@ def test_create_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -5953,7 +6637,7 @@ def test_create_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -5966,7 +6650,7 @@ def test_create_dialog_node_required_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'foo': 'bar'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6016,7 +6700,7 @@ def test_create_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6045,26 +6729,28 @@ def test_create_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6073,13 +6759,13 @@ def test_create_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6092,7 +6778,7 @@ def test_create_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6105,7 +6791,7 @@ def test_create_dialog_node_value_error(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'foo': 'bar'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6128,7 +6814,6 @@ def test_create_dialog_node_value_error(self): with pytest.raises(ValueError): _service.create_dialog_node(**req_copy) - def test_create_dialog_node_value_error_with_retries(self): # Enable retries and run test_create_dialog_node_value_error. _service.enable_retries() @@ -6150,7 +6835,7 @@ def test_get_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -6194,7 +6879,7 @@ def test_get_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -6232,7 +6917,7 @@ def test_get_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -6253,7 +6938,6 @@ def test_get_dialog_node_value_error(self): with pytest.raises(ValueError): _service.get_dialog_node(**req_copy) - def test_get_dialog_node_value_error_with_retries(self): # Enable retries and run test_get_dialog_node_value_error. _service.enable_retries() @@ -6275,26 +6959,28 @@ def test_update_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6303,13 +6989,13 @@ def test_update_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6322,7 +7008,7 @@ def test_update_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6336,7 +7022,7 @@ def test_update_dialog_node_all_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'foo': 'bar'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6393,7 +7079,7 @@ def test_update_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6422,26 +7108,28 @@ def test_update_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6450,13 +7138,13 @@ def test_update_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6469,7 +7157,7 @@ def test_update_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6483,7 +7171,7 @@ def test_update_dialog_node_required_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'foo': 'bar'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6534,7 +7222,7 @@ def test_update_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6563,26 +7251,28 @@ def test_update_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6591,13 +7281,13 @@ def test_update_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6610,7 +7300,7 @@ def test_update_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6624,7 +7314,7 @@ def test_update_dialog_node_value_error(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'foo': 'bar'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6647,7 +7337,6 @@ def test_update_dialog_node_value_error(self): with pytest.raises(ValueError): _service.update_dialog_node(**req_copy) - def test_update_dialog_node_value_error_with_retries(self): # Enable retries and run test_update_dialog_node_value_error. _service.enable_retries() @@ -6722,7 +7411,6 @@ def test_delete_dialog_node_value_error(self): with pytest.raises(ValueError): _service.delete_dialog_node(**req_copy) - def test_delete_dialog_node_value_error_with_retries(self): # Enable retries and run test_delete_dialog_node_value_error. _service.enable_retries() @@ -6754,7 +7442,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6805,7 +7493,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6841,7 +7529,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6860,7 +7548,6 @@ def test_list_logs_value_error(self): with pytest.raises(ValueError): _service.list_logs(**req_copy) - def test_list_logs_value_error_with_retries(self): # Enable retries and run test_list_logs_value_error. _service.enable_retries() @@ -6882,7 +7569,7 @@ def test_list_all_logs_all_params(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6931,7 +7618,7 @@ def test_list_all_logs_required_params(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6971,7 +7658,7 @@ def test_list_all_logs_value_error(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6990,7 +7677,6 @@ def test_list_all_logs_value_error(self): with pytest.raises(ValueError): _service.list_all_logs(**req_copy) - def test_list_all_logs_value_error_with_retries(self): # Enable retries and run test_list_all_logs_value_error. _service.enable_retries() @@ -7075,7 +7761,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -7483,7 +8168,7 @@ def test_context_serialization(self): # Construct a json representation of a Context model context_model_json = {} context_model_json['conversation_id'] = 'testString' - context_model_json['system'] = {} + context_model_json['system'] = {'foo': 'bar'} context_model_json['metadata'] = message_context_metadata_model context_model_json['foo'] = 'testString' @@ -7525,8 +8210,6 @@ def test_counterexample_serialization(self): # Construct a json representation of a Counterexample model counterexample_model_json = {} counterexample_model_json['text'] = 'testString' - counterexample_model_json['created'] = '2019-01-01T12:00:00Z' - counterexample_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Counterexample by calling from_dict on the json representation counterexample_model = Counterexample.from_dict(counterexample_model_json) @@ -7557,8 +8240,6 @@ def test_counterexample_collection_serialization(self): counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7602,21 +8283,17 @@ def test_create_entity_serialization(self): create_value_model = {} # CreateValue create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] - create_value_model['created'] = '2019-01-01T12:00:00Z' - create_value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateEntity model create_entity_model_json = {} create_entity_model_json['entity'] = 'testString' create_entity_model_json['description'] = 'testString' - create_entity_model_json['metadata'] = {} + create_entity_model_json['metadata'] = {'foo': 'bar'} create_entity_model_json['fuzzy_match'] = True - create_entity_model_json['created'] = '2019-01-01T12:00:00Z' - create_entity_model_json['updated'] = '2019-01-01T12:00:00Z' create_entity_model_json['values'] = [create_value_model] # Construct a model instance of CreateEntity by calling from_dict on the json representation @@ -7653,15 +8330,11 @@ def test_create_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateIntent model create_intent_model_json = {} create_intent_model_json['intent'] = 'testString' create_intent_model_json['description'] = 'testString' - create_intent_model_json['created'] = '2019-01-01T12:00:00Z' - create_intent_model_json['updated'] = '2019-01-01T12:00:00Z' create_intent_model_json['examples'] = [example_model] # Construct a model instance of CreateIntent by calling from_dict on the json representation @@ -7692,12 +8365,10 @@ def test_create_value_serialization(self): # Construct a json representation of a CreateValue model create_value_model_json = {} create_value_model_json['value'] = 'testString' - create_value_model_json['metadata'] = {} + create_value_model_json['metadata'] = {'foo': 'bar'} create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] - create_value_model_json['created'] = '2019-01-01T12:00:00Z' - create_value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of CreateValue by calling from_dict on the json representation create_value_model = CreateValue.from_dict(create_value_model_json) @@ -7726,29 +8397,30 @@ def test_dialog_node_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -7759,7 +8431,7 @@ def test_dialog_node_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7772,7 +8444,7 @@ def test_dialog_node_serialization(self): dialog_node_model_json['previous_sibling'] = 'testString' dialog_node_model_json['output'] = dialog_node_output_model dialog_node_model_json['context'] = dialog_node_context_model - dialog_node_model_json['metadata'] = {} + dialog_node_model_json['metadata'] = {'foo': 'bar'} dialog_node_model_json['next_step'] = dialog_node_next_step_model dialog_node_model_json['title'] = 'testString' dialog_node_model_json['type'] = 'standard' @@ -7784,9 +8456,6 @@ def test_dialog_node_serialization(self): dialog_node_model_json['digress_out_slots'] = 'not_allowed' dialog_node_model_json['user_label'] = 'testString' dialog_node_model_json['disambiguation_opt_out'] = False - dialog_node_model_json['disabled'] = True - dialog_node_model_json['created'] = '2019-01-01T12:00:00Z' - dialog_node_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of DialogNode by calling from_dict on the json representation dialog_node_model = DialogNode.from_dict(dialog_node_model_json) @@ -7817,7 +8486,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {} + dialog_node_action_model_json['parameters'] = {'foo': 'bar'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -7848,29 +8517,30 @@ def test_dialog_node_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -7881,7 +8551,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7893,7 +8563,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -7905,9 +8575,6 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7949,7 +8616,7 @@ def test_dialog_node_context_serialization(self): # Construct a json representation of a DialogNodeContext model dialog_node_context_model_json = {} - dialog_node_context_model_json['integrations'] = {} + dialog_node_context_model_json['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeContext by calling from_dict on the json representation @@ -8020,17 +8687,18 @@ def test_dialog_node_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -8038,7 +8706,7 @@ def test_dialog_node_output_serialization(self): # Construct a json representation of a DialogNodeOutput model dialog_node_output_model_json = {} dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model_json['integrations'] = {} + dialog_node_output_model_json['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model_json['foo'] = 'testString' @@ -8079,7 +8747,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -8141,8 +8809,6 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -8239,8 +8905,6 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -8393,8 +9057,6 @@ def test_dialog_suggestion_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -8459,7 +9121,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {} + dialog_suggestion_model_json['output'] = {'foo': 'bar'} dialog_suggestion_model_json['dialog_node'] = 'testString' # Construct a model instance of DialogSuggestion by calling from_dict on the json representation @@ -8493,8 +9155,6 @@ def test_dialog_suggestion_value_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -8585,21 +9245,17 @@ def test_entity_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Entity model entity_model_json = {} entity_model_json['entity'] = 'testString' entity_model_json['description'] = 'testString' - entity_model_json['metadata'] = {} + entity_model_json['metadata'] = {'foo': 'bar'} entity_model_json['fuzzy_match'] = True - entity_model_json['created'] = '2019-01-01T12:00:00Z' - entity_model_json['updated'] = '2019-01-01T12:00:00Z' entity_model_json['values'] = [value_model] # Construct a model instance of Entity by calling from_dict on the json representation @@ -8631,20 +9287,16 @@ def test_entity_collection_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'foo': 'bar'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] pagination_model = {} # Pagination @@ -8771,8 +9423,6 @@ def test_example_serialization(self): example_model_json = {} example_model_json['text'] = 'testString' example_model_json['mentions'] = [mention_model] - example_model_json['created'] = '2019-01-01T12:00:00Z' - example_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Example by calling from_dict on the json representation example_model = Example.from_dict(example_model_json) @@ -8808,8 +9458,6 @@ def test_example_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -8858,15 +9506,11 @@ def test_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Intent model intent_model_json = {} intent_model_json['intent'] = 'testString' intent_model_json['description'] = 'testString' - intent_model_json['created'] = '2019-01-01T12:00:00Z' - intent_model_json['updated'] = '2019-01-01T12:00:00Z' intent_model_json['examples'] = [example_model] # Construct a model instance of Intent by calling from_dict on the json representation @@ -8903,14 +9547,10 @@ def test_intent_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] pagination_model = {} # Pagination @@ -8957,8 +9597,6 @@ def test_log_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9020,7 +9658,7 @@ def test_log_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9039,24 +9677,12 @@ def test_log_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -9066,13 +9692,6 @@ def test_log_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] @@ -9080,7 +9699,6 @@ def test_log_serialization(self): message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model - message_request_model['actions'] = [dialog_node_action_model] message_request_model['user_id'] = 'testString' message_response_model = {} # MessageResponse @@ -9090,7 +9708,6 @@ def test_log_serialization(self): message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model - message_response_model['actions'] = [dialog_node_action_model] message_response_model['user_id'] = 'testString' # Construct a json representation of a Log model @@ -9134,8 +9751,6 @@ def test_log_collection_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9197,7 +9812,7 @@ def test_log_collection_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9216,24 +9831,12 @@ def test_log_collection_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -9243,13 +9846,6 @@ def test_log_collection_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] @@ -9257,7 +9853,6 @@ def test_log_collection_serialization(self): message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model - message_request_model['actions'] = [dialog_node_action_model] message_request_model['user_id'] = 'testString' message_response_model = {} # MessageResponse @@ -9267,7 +9862,6 @@ def test_log_collection_serialization(self): message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model - message_response_model['actions'] = [dialog_node_action_model] message_response_model['user_id'] = 'testString' log_model = {} # Log @@ -9478,8 +10072,6 @@ def test_message_input_serialization(self): message_input_model_json['text'] = 'testString' message_input_model_json['spelling_suggestions'] = False message_input_model_json['spelling_auto_correct'] = False - message_input_model_json['suggested_text'] = 'testString' - message_input_model_json['original_text'] = 'testString' message_input_model_json['foo'] = 'testString' # Construct a model instance of MessageInput by calling from_dict on the json representation @@ -9523,8 +10115,6 @@ def test_message_request_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9586,7 +10176,7 @@ def test_message_request_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9605,24 +10195,12 @@ def test_message_request_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -9632,13 +10210,6 @@ def test_message_request_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - # Construct a json representation of a MessageRequest model message_request_model_json = {} message_request_model_json['input'] = message_input_model @@ -9647,7 +10218,6 @@ def test_message_request_serialization(self): message_request_model_json['alternate_intents'] = False message_request_model_json['context'] = context_model message_request_model_json['output'] = output_data_model - message_request_model_json['actions'] = [dialog_node_action_model] message_request_model_json['user_id'] = 'testString' # Construct a model instance of MessageRequest by calling from_dict on the json representation @@ -9681,8 +10251,6 @@ def test_message_response_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9744,7 +10312,7 @@ def test_message_response_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9763,24 +10331,12 @@ def test_message_response_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -9790,13 +10346,6 @@ def test_message_response_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - # Construct a json representation of a MessageResponse model message_response_model_json = {} message_response_model_json['input'] = message_input_model @@ -9805,7 +10354,6 @@ def test_message_response_serialization(self): message_response_model_json['alternate_intents'] = False message_response_model_json['context'] = context_model message_response_model_json['output'] = output_data_model - message_response_model_json['actions'] = [dialog_node_action_model] message_response_model_json['user_id'] = 'testString' # Construct a model instance of MessageResponse by calling from_dict on the json representation @@ -9850,85 +10398,12 @@ def test_output_data_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - message_input_model = {} # MessageInput - message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = False - message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' - message_input_model['foo'] = 'testString' - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a json representation of a OutputData model @@ -10247,6 +10722,35 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json +class TestModel_StatusError(): + """ + Test Class for StatusError + """ + + def test_status_error_serialization(self): + """ + Test serialization/deserialization for StatusError + """ + + # Construct a json representation of a StatusError model + status_error_model_json = {} + status_error_model_json['message'] = 'testString' + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model = StatusError.from_dict(status_error_model_json) + assert status_error_model != False + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model_dict = StatusError.from_dict(status_error_model_json).__dict__ + status_error_model2 = StatusError(**status_error_model_dict) + + # Verify the model instances are equivalent + assert status_error_model == status_error_model2 + + # Convert model instance back to dict and verify no loss of data + status_error_model_json2 = status_error_model.to_dict() + assert status_error_model_json2 == status_error_model_json + class TestModel_Synonym(): """ Test Class for Synonym @@ -10260,8 +10764,6 @@ def test_synonym_serialization(self): # Construct a json representation of a Synonym model synonym_model_json = {} synonym_model_json['synonym'] = 'testString' - synonym_model_json['created'] = '2019-01-01T12:00:00Z' - synonym_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Synonym by calling from_dict on the json representation synonym_model = Synonym.from_dict(synonym_model_json) @@ -10292,8 +10794,6 @@ def test_synonym_collection_serialization(self): synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - synonym_model['created'] = '2019-01-01T12:00:00Z' - synonym_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -10336,12 +10836,10 @@ def test_value_serialization(self): # Construct a json representation of a Value model value_model_json = {} value_model_json['value'] = 'testString' - value_model_json['metadata'] = {} + value_model_json['metadata'] = {'foo': 'bar'} value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] - value_model_json['created'] = '2019-01-01T12:00:00Z' - value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Value by calling from_dict on the json representation value_model = Value.from_dict(value_model_json) @@ -10372,12 +10870,10 @@ def test_value_collection_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -10486,29 +10982,30 @@ def test_workspace_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -10519,7 +11016,7 @@ def test_workspace_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -10531,7 +11028,7 @@ def test_workspace_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -10543,14 +11040,9 @@ def test_workspace_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -10570,14 +11062,18 @@ def test_workspace_serialization(self): workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'testString' + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' webhook_header_model = {} # WebhookHeader @@ -10596,32 +11092,24 @@ def test_workspace_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'foo': 'bar'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] # Construct a json representation of a Workspace model @@ -10629,15 +11117,11 @@ def test_workspace_serialization(self): workspace_model_json['name'] = 'testString' workspace_model_json['description'] = 'testString' workspace_model_json['language'] = 'testString' - workspace_model_json['workspace_id'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['created'] = '2019-01-01T12:00:00Z' - workspace_model_json['updated'] = '2019-01-01T12:00:00Z' - workspace_model_json['metadata'] = {} + workspace_model_json['metadata'] = {'foo': 'bar'} workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model - workspace_model_json['status'] = 'Non Existent' workspace_model_json['webhooks'] = [webhook_model] workspace_model_json['intents'] = [intent_model] workspace_model_json['entities'] = [entity_model] @@ -10669,29 +11153,30 @@ def test_workspace_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -10702,7 +11187,7 @@ def test_workspace_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -10714,7 +11199,7 @@ def test_workspace_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -10726,14 +11211,9 @@ def test_workspace_collection_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -10753,14 +11233,18 @@ def test_workspace_collection_serialization(self): workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'testString' + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' webhook_header_model = {} # WebhookHeader @@ -10779,47 +11263,35 @@ def test_workspace_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'foo': 'bar'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] workspace_model = {} # Workspace workspace_model['name'] = 'testString' workspace_model['description'] = 'testString' workspace_model['language'] = 'testString' - workspace_model['workspace_id'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['created'] = '2019-01-01T12:00:00Z' - workspace_model['updated'] = '2019-01-01T12:00:00Z' - workspace_model['metadata'] = {} + workspace_model['metadata'] = {'foo': 'bar'} workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model - workspace_model['status'] = 'Non Existent' workspace_model['webhooks'] = [webhook_model] workspace_model['intents'] = [intent_model] workspace_model['entities'] = [entity_model] @@ -10852,6 +11324,37 @@ def test_workspace_collection_serialization(self): workspace_collection_model_json2 = workspace_collection_model.to_dict() assert workspace_collection_model_json2 == workspace_collection_model_json +class TestModel_WorkspaceCounts(): + """ + Test Class for WorkspaceCounts + """ + + def test_workspace_counts_serialization(self): + """ + Test serialization/deserialization for WorkspaceCounts + """ + + # Construct a json representation of a WorkspaceCounts model + workspace_counts_model_json = {} + workspace_counts_model_json['intent'] = 38 + workspace_counts_model_json['entity'] = 38 + workspace_counts_model_json['node'] = 38 + + # Construct a model instance of WorkspaceCounts by calling from_dict on the json representation + workspace_counts_model = WorkspaceCounts.from_dict(workspace_counts_model_json) + assert workspace_counts_model != False + + # Construct a model instance of WorkspaceCounts by calling from_dict on the json representation + workspace_counts_model_dict = WorkspaceCounts.from_dict(workspace_counts_model_json).__dict__ + workspace_counts_model2 = WorkspaceCounts(**workspace_counts_model_dict) + + # Verify the model instances are equivalent + assert workspace_counts_model == workspace_counts_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_counts_model_json2 = workspace_counts_model.to_dict() + assert workspace_counts_model_json2 == workspace_counts_model_json + class TestModel_WorkspaceSystemSettings(): """ Test Class for WorkspaceSystemSettings @@ -10882,15 +11385,19 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'testString' + # Construct a json representation of a WorkspaceSystemSettings model workspace_system_settings_model_json = {} workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model_json['human_agent_assist'] = {} + workspace_system_settings_model_json['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model_json['spelling_suggestions'] = False workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model_json['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model_json['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model_json['foo'] = 'testString' # Construct a model instance of WorkspaceSystemSettings by calling from_dict on the json representation @@ -10953,6 +11460,35 @@ def test_workspace_system_settings_disambiguation_serialization(self): workspace_system_settings_disambiguation_model_json2 = workspace_system_settings_disambiguation_model.to_dict() assert workspace_system_settings_disambiguation_model_json2 == workspace_system_settings_disambiguation_model_json +class TestModel_WorkspaceSystemSettingsNlp(): + """ + Test Class for WorkspaceSystemSettingsNlp + """ + + def test_workspace_system_settings_nlp_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettingsNlp + """ + + # Construct a json representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model_json = {} + workspace_system_settings_nlp_model_json['model'] = 'testString' + + # Construct a model instance of WorkspaceSystemSettingsNlp by calling from_dict on the json representation + workspace_system_settings_nlp_model = WorkspaceSystemSettingsNlp.from_dict(workspace_system_settings_nlp_model_json) + assert workspace_system_settings_nlp_model != False + + # Construct a model instance of WorkspaceSystemSettingsNlp by calling from_dict on the json representation + workspace_system_settings_nlp_model_dict = WorkspaceSystemSettingsNlp.from_dict(workspace_system_settings_nlp_model_json).__dict__ + workspace_system_settings_nlp_model2 = WorkspaceSystemSettingsNlp(**workspace_system_settings_nlp_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_nlp_model == workspace_system_settings_nlp_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_nlp_model_json2 = workspace_system_settings_nlp_model.to_dict() + assert workspace_system_settings_nlp_model_json2 == workspace_system_settings_nlp_model_json + class TestModel_WorkspaceSystemSettingsOffTopic(): """ Test Class for WorkspaceSystemSettingsOffTopic @@ -11062,7 +11598,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio by calling from_dict on the json representation @@ -11142,7 +11678,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' @@ -11265,8 +11801,6 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -11493,7 +12027,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined model dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['response_type'] = 'user_defined' - dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation @@ -11533,7 +12067,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_dialog_node_output_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo by calling from_dict on the json representation @@ -11573,7 +12107,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -11653,7 +12187,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' @@ -11778,8 +12312,6 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -11924,8 +12456,6 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -11989,7 +12519,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {} + dialog_suggestion_model['output'] = {'foo': 'bar'} dialog_suggestion_model['dialog_node'] = 'testString' response_generic_channel_model = {} # ResponseGenericChannel @@ -12071,7 +12601,7 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -12111,7 +12641,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 2542016ee..f0a15e812 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,7 +17,9 @@ Unit Tests for AssistantV2 """ +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import json import pytest @@ -31,7 +33,7 @@ _service = AssistantV2( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' @@ -64,6 +66,317 @@ def preprocess_url(operation_path: str): return re.compile(request_url.rstrip('/') + '/+') +############################################################################## +# Start of Service: Assistants +############################################################################## +# region + +class TestCreateAssistant(): + """ + Test Class for create_assistant + """ + + @responses.activate + def test_create_assistant_all_params(self): + """ + create_assistant() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + language = 'testString' + name = 'testString' + description = 'testString' + + # Invoke method + response = _service.create_assistant( + language=language, + name=name, + description=description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['language'] == 'testString' + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + + def test_create_assistant_all_params_with_retries(self): + # Enable retries and run test_create_assistant_all_params. + _service.enable_retries() + self.test_create_assistant_all_params() + + # Disable retries and run test_create_assistant_all_params. + _service.disable_retries() + self.test_create_assistant_all_params() + + @responses.activate + def test_create_assistant_required_params(self): + """ + test_create_assistant_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.create_assistant() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_create_assistant_required_params_with_retries(self): + # Enable retries and run test_create_assistant_required_params. + _service.enable_retries() + self.test_create_assistant_required_params() + + # Disable retries and run test_create_assistant_required_params. + _service.disable_retries() + self.test_create_assistant_required_params() + + @responses.activate + def test_create_assistant_value_error(self): + """ + test_create_assistant_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_assistant(**req_copy) + + def test_create_assistant_value_error_with_retries(self): + # Enable retries and run test_create_assistant_value_error. + _service.enable_retries() + self.test_create_assistant_value_error() + + # Disable retries and run test_create_assistant_value_error. + _service.disable_retries() + self.test_create_assistant_value_error() + +class TestListAssistants(): + """ + Test Class for list_assistants + """ + + @responses.activate + def test_list_assistants_all_params(self): + """ + list_assistants() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + page_limit = 38 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False + + # Invoke method + response = _service.list_assistants( + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_list_assistants_all_params_with_retries(self): + # Enable retries and run test_list_assistants_all_params. + _service.enable_retries() + self.test_list_assistants_all_params() + + # Disable retries and run test_list_assistants_all_params. + _service.disable_retries() + self.test_list_assistants_all_params() + + @responses.activate + def test_list_assistants_required_params(self): + """ + test_list_assistants_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_assistants() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_assistants_required_params_with_retries(self): + # Enable retries and run test_list_assistants_required_params. + _service.enable_retries() + self.test_list_assistants_required_params() + + # Disable retries and run test_list_assistants_required_params. + _service.disable_retries() + self.test_list_assistants_required_params() + + @responses.activate + def test_list_assistants_value_error(self): + """ + test_list_assistants_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_assistants(**req_copy) + + def test_list_assistants_value_error_with_retries(self): + # Enable retries and run test_list_assistants_value_error. + _service.enable_retries() + self.test_list_assistants_value_error() + + # Disable retries and run test_list_assistants_value_error. + _service.disable_retries() + self.test_list_assistants_value_error() + +class TestDeleteAssistant(): + """ + Test Class for delete_assistant + """ + + @responses.activate + def test_delete_assistant_all_params(self): + """ + delete_assistant() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.delete_assistant( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_assistant_all_params_with_retries(self): + # Enable retries and run test_delete_assistant_all_params. + _service.enable_retries() + self.test_delete_assistant_all_params() + + # Disable retries and run test_delete_assistant_all_params. + _service.disable_retries() + self.test_delete_assistant_all_params() + + @responses.activate + def test_delete_assistant_value_error(self): + """ + test_delete_assistant_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_assistant(**req_copy) + + def test_delete_assistant_value_error_with_retries(self): + # Enable retries and run test_delete_assistant_value_error. + _service.enable_retries() + self.test_delete_assistant_value_error() + + # Disable retries and run test_delete_assistant_value_error. + _service.disable_retries() + self.test_delete_assistant_value_error() + +# endregion +############################################################################## +# End of Service: Assistants +############################################################################## + ############################################################################## # Start of Service: Sessions ############################################################################## @@ -88,18 +401,29 @@ def test_create_session_all_params(self): content_type='application/json', status=201) + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + # Set up parameter values assistant_id = 'testString' + analytics = request_analytics_model # Invoke method response = _service.create_session( assistant_id, + analytics=analytics, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['analytics'] == request_analytics_model def test_create_session_all_params_with_retries(self): # Enable retries and run test_create_session_all_params. @@ -110,6 +434,42 @@ def test_create_session_all_params_with_retries(self): _service.disable_retries() self.test_create_session_all_params() + @responses.activate + def test_create_session_required_params(self): + """ + test_create_session_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/sessions') + mock_response = '{"session_id": "session_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.create_session( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + def test_create_session_required_params_with_retries(self): + # Enable retries and run test_create_session_required_params. + _service.enable_retries() + self.test_create_session_required_params() + + # Disable retries and run test_create_session_required_params. + _service.disable_retries() + self.test_create_session_required_params() + @responses.activate def test_create_session_value_error(self): """ @@ -136,7 +496,6 @@ def test_create_session_value_error(self): with pytest.raises(ValueError): _service.create_session(**req_copy) - def test_create_session_value_error_with_retries(self): # Enable retries and run test_create_session_value_error. _service.enable_retries() @@ -211,7 +570,6 @@ def test_delete_session_value_error(self): with pytest.raises(ValueError): _service.delete_session(**req_copy) - def test_delete_session_value_error_with_retries(self): # Enable retries and run test_delete_session_value_error. _service.enable_retries() @@ -243,7 +601,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -254,6 +612,7 @@ def test_message_all_params(self): runtime_intent_model = {} runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' # Construct a dict representation of a CaptureGroup model capture_group_model = {} @@ -308,12 +667,19 @@ def test_message_all_params(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' # Construct a dict representation of a MessageInputAttachment model message_input_attachment_model = {} message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + # Construct a dict representation of a MessageInputOptionsSpelling model message_input_options_spelling_model = {} message_input_options_spelling_model['suggestions'] = True @@ -336,6 +702,7 @@ def test_message_all_params(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model # Construct a dict representation of a MessageContextGlobalSystem model @@ -358,16 +725,28 @@ def test_message_all_params(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkill model - message_context_skill_model = {} - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextSkillDialog model + message_context_skill_dialog_model = {} + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextSkillAction model + message_context_skill_action_model = {} + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model # Construct a dict representation of a MessageContext model message_context_model = {} message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'foo': 'bar'} # Set up parameter values assistant_id = 'testString' @@ -411,7 +790,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -449,7 +828,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -470,7 +849,6 @@ def test_message_value_error(self): with pytest.raises(ValueError): _service.message(**req_copy) - def test_message_value_error_with_retries(self): # Enable retries and run test_message_value_error. _service.enable_retries() @@ -492,7 +870,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -503,6 +881,7 @@ def test_message_stateless_all_params(self): runtime_intent_model = {} runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' # Construct a dict representation of a CaptureGroup model capture_group_model = {} @@ -557,12 +936,19 @@ def test_message_stateless_all_params(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' # Construct a dict representation of a MessageInputAttachment model message_input_attachment_model = {} message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + # Construct a dict representation of a MessageInputOptionsSpelling model message_input_options_spelling_model = {} message_input_options_spelling_model['suggestions'] = True @@ -583,6 +969,7 @@ def test_message_stateless_all_params(self): message_input_stateless_model['entities'] = [runtime_entity_model] message_input_stateless_model['suggestion_id'] = 'testString' message_input_stateless_model['attachments'] = [message_input_attachment_model] + message_input_stateless_model['analytics'] = request_analytics_model message_input_stateless_model['options'] = message_input_options_stateless_model # Construct a dict representation of a MessageContextGlobalSystem model @@ -606,16 +993,28 @@ def test_message_stateless_all_params(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkill model - message_context_skill_model = {} - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextSkillDialog model + message_context_skill_dialog_model = {} + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextSkillAction model + message_context_skill_action_model = {} + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model # Construct a dict representation of a MessageContextStateless model message_context_stateless_model = {} message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = {} - message_context_stateless_model['integrations'] = { 'foo': 'bar' } + message_context_stateless_model['skills'] = message_context_skills_model + message_context_stateless_model['integrations'] = {'foo': 'bar'} # Set up parameter values assistant_id = 'testString' @@ -657,7 +1056,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -693,7 +1092,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -712,7 +1111,6 @@ def test_message_stateless_value_error(self): with pytest.raises(ValueError): _service.message_stateless(**req_copy) - def test_message_stateless_value_error_with_retries(self): # Enable retries and run test_message_stateless_value_error. _service.enable_retries() @@ -744,7 +1142,7 @@ def test_bulk_classify_all_params(self): """ # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -762,7 +1160,7 @@ def test_bulk_classify_all_params(self): # Invoke method response = _service.bulk_classify( skill_id, - input=input, + input, headers={} ) @@ -783,68 +1181,37 @@ def test_bulk_classify_all_params_with_retries(self): self.test_bulk_classify_all_params() @responses.activate - def test_bulk_classify_required_params(self): + def test_bulk_classify_value_error(self): """ - test_bulk_classify_required_params() + test_bulk_classify_value_error() """ # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Set up parameter values - skill_id = 'testString' - - # Invoke method - response = _service.bulk_classify( - skill_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_bulk_classify_required_params_with_retries(self): - # Enable retries and run test_bulk_classify_required_params. - _service.enable_retries() - self.test_bulk_classify_required_params() - - # Disable retries and run test_bulk_classify_required_params. - _service.disable_retries() - self.test_bulk_classify_required_params() - - @responses.activate - def test_bulk_classify_value_error(self): - """ - test_bulk_classify_value_error() - """ - # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' # Set up parameter values skill_id = 'testString' + input = [bulk_classify_utterance_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "skill_id": skill_id, + "input": input, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.bulk_classify(**req_copy) - def test_bulk_classify_value_error_with_retries(self): # Enable retries and run test_bulk_classify_value_error. _service.enable_retries() @@ -876,7 +1243,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -927,7 +1294,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -963,7 +1330,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -982,7 +1349,6 @@ def test_list_logs_value_error(self): with pytest.raises(ValueError): _service.list_logs(**req_copy) - def test_list_logs_value_error_with_retries(self): # Enable retries and run test_list_logs_value_error. _service.enable_retries() @@ -1067,7 +1433,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -1082,488 +1447,3119 @@ def test_delete_user_data_value_error_with_retries(self): # End of Service: UserData ############################################################################## - ############################################################################## -# Start of Model Tests +# Start of Service: Environments ############################################################################## # region -class TestModel_AgentAvailabilityMessage(): + +class TestListEnvironments(): """ - Test Class for AgentAvailabilityMessage + Test Class for list_environments """ - def test_agent_availability_message_serialization(self): + @responses.activate + def test_list_environments_all_params(self): """ - Test serialization/deserialization for AgentAvailabilityMessage + list_environments() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct a json representation of a AgentAvailabilityMessage model - agent_availability_message_model_json = {} - agent_availability_message_model_json['message'] = 'testString' - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) - assert agent_availability_message_model != False + # Set up parameter values + assistant_id = 'testString' + page_limit = 38 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ - agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + # Invoke method + response = _service.list_environments( + assistant_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) - # Verify the model instances are equivalent - assert agent_availability_message_model == agent_availability_message_model2 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Convert model instance back to dict and verify no loss of data - agent_availability_message_model_json2 = agent_availability_message_model.to_dict() - assert agent_availability_message_model_json2 == agent_availability_message_model_json + def test_list_environments_all_params_with_retries(self): + # Enable retries and run test_list_environments_all_params. + _service.enable_retries() + self.test_list_environments_all_params() -class TestModel_BulkClassifyOutput(): - """ - Test Class for BulkClassifyOutput - """ + # Disable retries and run test_list_environments_all_params. + _service.disable_retries() + self.test_list_environments_all_params() - def test_bulk_classify_output_serialization(self): + @responses.activate + def test_list_environments_required_params(self): """ - Test serialization/deserialization for BulkClassifyOutput + test_list_environments_required_params() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct dict forms of any model objects needed in order to build this model. - - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Set up parameter values + assistant_id = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Invoke method + response = _service.list_environments( + assistant_id, + headers={} + ) - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + def test_list_environments_required_params_with_retries(self): + # Enable retries and run test_list_environments_required_params. + _service.enable_retries() + self.test_list_environments_required_params() - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 + # Disable retries and run test_list_environments_required_params. + _service.disable_retries() + self.test_list_environments_required_params() - # Construct a json representation of a BulkClassifyOutput model - bulk_classify_output_model_json = {} - bulk_classify_output_model_json['input'] = bulk_classify_utterance_model - bulk_classify_output_model_json['entities'] = [runtime_entity_model] - bulk_classify_output_model_json['intents'] = [runtime_intent_model] + @responses.activate + def test_list_environments_value_error(self): + """ + test_list_environments_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) - assert bulk_classify_output_model != False + # Set up parameter values + assistant_id = 'testString' - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ - bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_environments(**req_copy) - # Verify the model instances are equivalent - assert bulk_classify_output_model == bulk_classify_output_model2 + def test_list_environments_value_error_with_retries(self): + # Enable retries and run test_list_environments_value_error. + _service.enable_retries() + self.test_list_environments_value_error() - # Convert model instance back to dict and verify no loss of data - bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() - assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + # Disable retries and run test_list_environments_value_error. + _service.disable_retries() + self.test_list_environments_value_error() -class TestModel_BulkClassifyResponse(): +class TestGetEnvironment(): """ - Test Class for BulkClassifyResponse + Test Class for get_environment """ - def test_bulk_classify_response_serialization(self): + @responses.activate + def test_get_environment_all_params(self): """ - Test serialization/deserialization for BulkClassifyResponse + get_environment() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct dict forms of any model objects needed in order to build this model. + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + include_audit = False - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' + # Invoke method + response = _service.get_environment( + assistant_id, + environment_id, + include_audit=include_audit, + headers={} + ) - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + def test_get_environment_all_params_with_retries(self): + # Enable retries and run test_get_environment_all_params. + _service.enable_retries() + self.test_get_environment_all_params() - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - - bulk_classify_output_model = {} # BulkClassifyOutput - bulk_classify_output_model['input'] = bulk_classify_utterance_model - bulk_classify_output_model['entities'] = [runtime_entity_model] - bulk_classify_output_model['intents'] = [runtime_intent_model] + # Disable retries and run test_get_environment_all_params. + _service.disable_retries() + self.test_get_environment_all_params() - # Construct a json representation of a BulkClassifyResponse model - bulk_classify_response_model_json = {} - bulk_classify_response_model_json['output'] = [bulk_classify_output_model] + @responses.activate + def test_get_environment_required_params(self): + """ + test_get_environment_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation - bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) - assert bulk_classify_response_model != False + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' - # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation - bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ - bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) + # Invoke method + response = _service.get_environment( + assistant_id, + environment_id, + headers={} + ) - # Verify the model instances are equivalent - assert bulk_classify_response_model == bulk_classify_response_model2 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - # Convert model instance back to dict and verify no loss of data - bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() - assert bulk_classify_response_model_json2 == bulk_classify_response_model_json + def test_get_environment_required_params_with_retries(self): + # Enable retries and run test_get_environment_required_params. + _service.enable_retries() + self.test_get_environment_required_params() -class TestModel_BulkClassifyUtterance(): - """ - Test Class for BulkClassifyUtterance - """ + # Disable retries and run test_get_environment_required_params. + _service.disable_retries() + self.test_get_environment_required_params() - def test_bulk_classify_utterance_serialization(self): + @responses.activate + def test_get_environment_value_error(self): """ - Test serialization/deserialization for BulkClassifyUtterance + test_get_environment_value_error() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct a json representation of a BulkClassifyUtterance model - bulk_classify_utterance_model_json = {} - bulk_classify_utterance_model_json['text'] = 'testString' - - # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation - bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) - assert bulk_classify_utterance_model != False + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' - # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation - bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ - bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_environment(**req_copy) - # Verify the model instances are equivalent - assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + def test_get_environment_value_error_with_retries(self): + # Enable retries and run test_get_environment_value_error. + _service.enable_retries() + self.test_get_environment_value_error() - # Convert model instance back to dict and verify no loss of data - bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() - assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + # Disable retries and run test_get_environment_value_error. + _service.disable_retries() + self.test_get_environment_value_error() -class TestModel_CaptureGroup(): +class TestUpdateEnvironment(): """ - Test Class for CaptureGroup + Test Class for update_environment """ - def test_capture_group_serialization(self): + @responses.activate + def test_update_environment_all_params(self): """ - Test serialization/deserialization for CaptureGroup + update_environment() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct a json representation of a CaptureGroup model - capture_group_model_json = {} - capture_group_model_json['group'] = 'testString' - capture_group_model_json['location'] = [38] + # Construct a dict representation of a EnvironmentSkill model + environment_skill_model = {} + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' - # Construct a model instance of CaptureGroup by calling from_dict on the json representation - capture_group_model = CaptureGroup.from_dict(capture_group_model_json) - assert capture_group_model != False + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + name = 'testString' + description = 'testString' + session_timeout = 10 + skill_references = [environment_skill_model] - # Construct a model instance of CaptureGroup by calling from_dict on the json representation - capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ - capture_group_model2 = CaptureGroup(**capture_group_model_dict) + # Invoke method + response = _service.update_environment( + assistant_id, + environment_id, + name=name, + description=description, + session_timeout=session_timeout, + skill_references=skill_references, + headers={} + ) - # Verify the model instances are equivalent - assert capture_group_model == capture_group_model2 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['session_timeout'] == 10 + assert req_body['skill_references'] == [environment_skill_model] - # Convert model instance back to dict and verify no loss of data - capture_group_model_json2 = capture_group_model.to_dict() - assert capture_group_model_json2 == capture_group_model_json + def test_update_environment_all_params_with_retries(self): + # Enable retries and run test_update_environment_all_params. + _service.enable_retries() + self.test_update_environment_all_params() -class TestModel_ChannelTransferInfo(): - """ - Test Class for ChannelTransferInfo - """ + # Disable retries and run test_update_environment_all_params. + _service.disable_retries() + self.test_update_environment_all_params() - def test_channel_transfer_info_serialization(self): + @responses.activate + def test_update_environment_required_params(self): """ - Test serialization/deserialization for ChannelTransferInfo + test_update_environment_required_params() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct dict forms of any model objects needed in order to build this model. - - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a json representation of a ChannelTransferInfo model - channel_transfer_info_model_json = {} - channel_transfer_info_model_json['target'] = channel_transfer_target_model - - # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation - channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) - assert channel_transfer_info_model != False + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' - # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation - channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ - channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + # Invoke method + response = _service.update_environment( + assistant_id, + environment_id, + headers={} + ) - # Verify the model instances are equivalent - assert channel_transfer_info_model == channel_transfer_info_model2 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - # Convert model instance back to dict and verify no loss of data - channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() - assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + def test_update_environment_required_params_with_retries(self): + # Enable retries and run test_update_environment_required_params. + _service.enable_retries() + self.test_update_environment_required_params() -class TestModel_ChannelTransferTarget(): - """ - Test Class for ChannelTransferTarget - """ + # Disable retries and run test_update_environment_required_params. + _service.disable_retries() + self.test_update_environment_required_params() - def test_channel_transfer_target_serialization(self): + @responses.activate + def test_update_environment_value_error(self): """ - Test serialization/deserialization for ChannelTransferTarget + test_update_environment_value_error() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct dict forms of any model objects needed in order to build this model. - - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' - # Construct a json representation of a ChannelTransferTarget model - channel_transfer_target_model_json = {} - channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_environment(**req_copy) - # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation - channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) - assert channel_transfer_target_model != False + def test_update_environment_value_error_with_retries(self): + # Enable retries and run test_update_environment_value_error. + _service.enable_retries() + self.test_update_environment_value_error() - # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation - channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ - channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) + # Disable retries and run test_update_environment_value_error. + _service.disable_retries() + self.test_update_environment_value_error() - # Verify the model instances are equivalent - assert channel_transfer_target_model == channel_transfer_target_model2 +# endregion +############################################################################## +# End of Service: Environments +############################################################################## - # Convert model instance back to dict and verify no loss of data - channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() - assert channel_transfer_target_model_json2 == channel_transfer_target_model_json +############################################################################## +# Start of Service: Releases +############################################################################## +# region -class TestModel_ChannelTransferTargetChat(): +class TestCreateRelease(): """ - Test Class for ChannelTransferTargetChat + Test Class for create_release """ - def test_channel_transfer_target_chat_serialization(self): + @responses.activate + def test_create_release_all_params(self): """ - Test serialization/deserialization for ChannelTransferTargetChat + create_release() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) - # Construct a json representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model_json = {} - channel_transfer_target_chat_model_json['url'] = 'testString' + # Set up parameter values + assistant_id = 'testString' + description = 'testString' - # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation - channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) - assert channel_transfer_target_chat_model != False + # Invoke method + response = _service.create_release( + assistant_id, + description=description, + headers={} + ) - # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['description'] == 'testString' + + def test_create_release_all_params_with_retries(self): + # Enable retries and run test_create_release_all_params. + _service.enable_retries() + self.test_create_release_all_params() + + # Disable retries and run test_create_release_all_params. + _service.disable_retries() + self.test_create_release_all_params() + + @responses.activate + def test_create_release_required_params(self): + """ + test_create_release_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.create_release( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_create_release_required_params_with_retries(self): + # Enable retries and run test_create_release_required_params. + _service.enable_retries() + self.test_create_release_required_params() + + # Disable retries and run test_create_release_required_params. + _service.disable_retries() + self.test_create_release_required_params() + + @responses.activate + def test_create_release_value_error(self): + """ + test_create_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_release(**req_copy) + + def test_create_release_value_error_with_retries(self): + # Enable retries and run test_create_release_value_error. + _service.enable_retries() + self.test_create_release_value_error() + + # Disable retries and run test_create_release_value_error. + _service.disable_retries() + self.test_create_release_value_error() + +class TestListReleases(): + """ + Test Class for list_releases + """ + + @responses.activate + def test_list_releases_all_params(self): + """ + list_releases() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + page_limit = 38 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False + + # Invoke method + response = _service.list_releases( + assistant_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_list_releases_all_params_with_retries(self): + # Enable retries and run test_list_releases_all_params. + _service.enable_retries() + self.test_list_releases_all_params() + + # Disable retries and run test_list_releases_all_params. + _service.disable_retries() + self.test_list_releases_all_params() + + @responses.activate + def test_list_releases_required_params(self): + """ + test_list_releases_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.list_releases( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_releases_required_params_with_retries(self): + # Enable retries and run test_list_releases_required_params. + _service.enable_retries() + self.test_list_releases_required_params() + + # Disable retries and run test_list_releases_required_params. + _service.disable_retries() + self.test_list_releases_required_params() + + @responses.activate + def test_list_releases_value_error(self): + """ + test_list_releases_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_releases(**req_copy) + + def test_list_releases_value_error_with_retries(self): + # Enable retries and run test_list_releases_value_error. + _service.enable_retries() + self.test_list_releases_value_error() + + # Disable retries and run test_list_releases_value_error. + _service.disable_retries() + self.test_list_releases_value_error() + +class TestGetRelease(): + """ + Test Class for get_release + """ + + @responses.activate + def test_get_release_all_params(self): + """ + get_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + include_audit = False + + # Invoke method + response = _service.get_release( + assistant_id, + release, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_get_release_all_params_with_retries(self): + # Enable retries and run test_get_release_all_params. + _service.enable_retries() + self.test_get_release_all_params() + + # Disable retries and run test_get_release_all_params. + _service.disable_retries() + self.test_get_release_all_params() + + @responses.activate + def test_get_release_required_params(self): + """ + test_get_release_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Invoke method + response = _service.get_release( + assistant_id, + release, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_release_required_params_with_retries(self): + # Enable retries and run test_get_release_required_params. + _service.enable_retries() + self.test_get_release_required_params() + + # Disable retries and run test_get_release_required_params. + _service.disable_retries() + self.test_get_release_required_params() + + @responses.activate + def test_get_release_value_error(self): + """ + test_get_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "release": release, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_release(**req_copy) + + def test_get_release_value_error_with_retries(self): + # Enable retries and run test_get_release_value_error. + _service.enable_retries() + self.test_get_release_value_error() + + # Disable retries and run test_get_release_value_error. + _service.disable_retries() + self.test_get_release_value_error() + +class TestDeleteRelease(): + """ + Test Class for delete_release + """ + + @responses.activate + def test_delete_release_all_params(self): + """ + delete_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Invoke method + response = _service.delete_release( + assistant_id, + release, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_release_all_params_with_retries(self): + # Enable retries and run test_delete_release_all_params. + _service.enable_retries() + self.test_delete_release_all_params() + + # Disable retries and run test_delete_release_all_params. + _service.disable_retries() + self.test_delete_release_all_params() + + @responses.activate + def test_delete_release_value_error(self): + """ + test_delete_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "release": release, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_release(**req_copy) + + def test_delete_release_value_error_with_retries(self): + # Enable retries and run test_delete_release_value_error. + _service.enable_retries() + self.test_delete_release_value_error() + + # Disable retries and run test_delete_release_value_error. + _service.disable_retries() + self.test_delete_release_value_error() + +class TestDeployRelease(): + """ + Test Class for deploy_release + """ + + @responses.activate + def test_deploy_release_all_params(self): + """ + deploy_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + include_audit = False + + # Invoke method + response = _service.deploy_release( + assistant_id, + release, + environment_id, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' + + def test_deploy_release_all_params_with_retries(self): + # Enable retries and run test_deploy_release_all_params. + _service.enable_retries() + self.test_deploy_release_all_params() + + # Disable retries and run test_deploy_release_all_params. + _service.disable_retries() + self.test_deploy_release_all_params() + + @responses.activate + def test_deploy_release_required_params(self): + """ + test_deploy_release_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + + # Invoke method + response = _service.deploy_release( + assistant_id, + release, + environment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' + + def test_deploy_release_required_params_with_retries(self): + # Enable retries and run test_deploy_release_required_params. + _service.enable_retries() + self.test_deploy_release_required_params() + + # Disable retries and run test_deploy_release_required_params. + _service.disable_retries() + self.test_deploy_release_required_params() + + @responses.activate + def test_deploy_release_value_error(self): + """ + test_deploy_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "release": release, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.deploy_release(**req_copy) + + def test_deploy_release_value_error_with_retries(self): + # Enable retries and run test_deploy_release_value_error. + _service.enable_retries() + self.test_deploy_release_value_error() + + # Disable retries and run test_deploy_release_value_error. + _service.disable_retries() + self.test_deploy_release_value_error() + +# endregion +############################################################################## +# End of Service: Releases +############################################################################## + +############################################################################## +# Start of Service: Skills +############################################################################## +# region + +class TestGetSkill(): + """ + Test Class for get_skill + """ + + @responses.activate + def test_get_skill_all_params(self): + """ + get_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Invoke method + response = _service.get_skill( + assistant_id, + skill_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_skill_all_params_with_retries(self): + # Enable retries and run test_get_skill_all_params. + _service.enable_retries() + self.test_get_skill_all_params() + + # Disable retries and run test_get_skill_all_params. + _service.disable_retries() + self.test_get_skill_all_params() + + @responses.activate + def test_get_skill_value_error(self): + """ + test_get_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_skill(**req_copy) + + def test_get_skill_value_error_with_retries(self): + # Enable retries and run test_get_skill_value_error. + _service.enable_retries() + self.test_get_skill_value_error() + + # Disable retries and run test_get_skill_value_error. + _service.disable_retries() + self.test_get_skill_value_error() + +class TestUpdateSkill(): + """ + Test Class for update_skill + """ + + @responses.activate + def test_update_skill_all_params(self): + """ + update_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'foo': 'bar'} + dialog_settings = {'foo': 'bar'} + search_settings = search_settings_model + + # Invoke method + response = _service.update_skill( + assistant_id, + skill_id, + name=name, + description=description, + workspace=workspace, + dialog_settings=dialog_settings, + search_settings=search_settings, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['workspace'] == {'foo': 'bar'} + assert req_body['dialog_settings'] == {'foo': 'bar'} + assert req_body['search_settings'] == search_settings_model + + def test_update_skill_all_params_with_retries(self): + # Enable retries and run test_update_skill_all_params. + _service.enable_retries() + self.test_update_skill_all_params() + + # Disable retries and run test_update_skill_all_params. + _service.disable_retries() + self.test_update_skill_all_params() + + @responses.activate + def test_update_skill_value_error(self): + """ + test_update_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'foo': 'bar'} + dialog_settings = {'foo': 'bar'} + search_settings = search_settings_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_skill(**req_copy) + + def test_update_skill_value_error_with_retries(self): + # Enable retries and run test_update_skill_value_error. + _service.enable_retries() + self.test_update_skill_value_error() + + # Disable retries and run test_update_skill_value_error. + _service.disable_retries() + self.test_update_skill_value_error() + +class TestExportSkills(): + """ + Test Class for export_skills + """ + + @responses.activate + def test_export_skills_all_params(self): + """ + export_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + include_audit = False + + # Invoke method + response = _service.export_skills( + assistant_id, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_export_skills_all_params_with_retries(self): + # Enable retries and run test_export_skills_all_params. + _service.enable_retries() + self.test_export_skills_all_params() + + # Disable retries and run test_export_skills_all_params. + _service.disable_retries() + self.test_export_skills_all_params() + + @responses.activate + def test_export_skills_required_params(self): + """ + test_export_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.export_skills( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_export_skills_required_params_with_retries(self): + # Enable retries and run test_export_skills_required_params. + _service.enable_retries() + self.test_export_skills_required_params() + + # Disable retries and run test_export_skills_required_params. + _service.disable_retries() + self.test_export_skills_required_params() + + @responses.activate + def test_export_skills_value_error(self): + """ + test_export_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.export_skills(**req_copy) + + def test_export_skills_value_error_with_retries(self): + # Enable retries and run test_export_skills_value_error. + _service.enable_retries() + self.test_export_skills_value_error() + + # Disable retries and run test_export_skills_value_error. + _service.disable_retries() + self.test_export_skills_value_error() + +class TestImportSkills(): + """ + Test Class for import_skills + """ + + @responses.activate + def test_import_skills_all_params(self): + """ + import_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'foo': 'bar'} + skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + include_audit = False + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_all_params_with_retries(self): + # Enable retries and run test_import_skills_all_params. + _service.enable_retries() + self.test_import_skills_all_params() + + # Disable retries and run test_import_skills_all_params. + _service.disable_retries() + self.test_import_skills_all_params() + + @responses.activate + def test_import_skills_required_params(self): + """ + test_import_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'foo': 'bar'} + skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_required_params_with_retries(self): + # Enable retries and run test_import_skills_required_params. + _service.enable_retries() + self.test_import_skills_required_params() + + # Disable retries and run test_import_skills_required_params. + _service.disable_retries() + self.test_import_skills_required_params() + + @responses.activate + def test_import_skills_value_error(self): + """ + test_import_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'foo': 'bar'} + skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "assistant_skills": assistant_skills, + "assistant_state": assistant_state, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.import_skills(**req_copy) + + def test_import_skills_value_error_with_retries(self): + # Enable retries and run test_import_skills_value_error. + _service.enable_retries() + self.test_import_skills_value_error() + + # Disable retries and run test_import_skills_value_error. + _service.disable_retries() + self.test_import_skills_value_error() + +class TestImportSkillsStatus(): + """ + Test Class for import_skills_status + """ + + @responses.activate + def test_import_skills_status_all_params(self): + """ + import_skills_status() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.import_skills_status( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_import_skills_status_all_params_with_retries(self): + # Enable retries and run test_import_skills_status_all_params. + _service.enable_retries() + self.test_import_skills_status_all_params() + + # Disable retries and run test_import_skills_status_all_params. + _service.disable_retries() + self.test_import_skills_status_all_params() + + @responses.activate + def test_import_skills_status_value_error(self): + """ + test_import_skills_status_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.import_skills_status(**req_copy) + + def test_import_skills_status_value_error_with_retries(self): + # Enable retries and run test_import_skills_status_value_error. + _service.enable_retries() + self.test_import_skills_status_value_error() + + # Disable retries and run test_import_skills_status_value_error. + _service.disable_retries() + self.test_import_skills_status_value_error() + +# endregion +############################################################################## +# End of Service: Skills +############################################################################## + + +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestModel_AgentAvailabilityMessage(): + """ + Test Class for AgentAvailabilityMessage + """ + + def test_agent_availability_message_serialization(self): + """ + Test serialization/deserialization for AgentAvailabilityMessage + """ + + # Construct a json representation of a AgentAvailabilityMessage model + agent_availability_message_model_json = {} + agent_availability_message_model_json['message'] = 'testString' + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) + assert agent_availability_message_model != False + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ + agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + + # Verify the model instances are equivalent + assert agent_availability_message_model == agent_availability_message_model2 + + # Convert model instance back to dict and verify no loss of data + agent_availability_message_model_json2 = agent_availability_message_model.to_dict() + assert agent_availability_message_model_json2 == agent_availability_message_model_json + +class TestModel_AssistantCollection(): + """ + Test Class for AssistantCollection + """ + + def test_assistant_collection_serialization(self): + """ + Test serialization/deserialization for AssistantCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + assistant_data_model = {} # AssistantData + assistant_data_model['name'] = 'testString' + assistant_data_model['description'] = 'testString' + assistant_data_model['language'] = 'testString' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a AssistantCollection model + assistant_collection_model_json = {} + assistant_collection_model_json['assistants'] = [assistant_data_model] + assistant_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model = AssistantCollection.from_dict(assistant_collection_model_json) + assert assistant_collection_model != False + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model_dict = AssistantCollection.from_dict(assistant_collection_model_json).__dict__ + assistant_collection_model2 = AssistantCollection(**assistant_collection_model_dict) + + # Verify the model instances are equivalent + assert assistant_collection_model == assistant_collection_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_collection_model_json2 = assistant_collection_model.to_dict() + assert assistant_collection_model_json2 == assistant_collection_model_json + +class TestModel_AssistantData(): + """ + Test Class for AssistantData + """ + + def test_assistant_data_serialization(self): + """ + Test serialization/deserialization for AssistantData + """ + + # Construct a json representation of a AssistantData model + assistant_data_model_json = {} + assistant_data_model_json['name'] = 'testString' + assistant_data_model_json['description'] = 'testString' + assistant_data_model_json['language'] = 'testString' + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model = AssistantData.from_dict(assistant_data_model_json) + assert assistant_data_model != False + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model_dict = AssistantData.from_dict(assistant_data_model_json).__dict__ + assistant_data_model2 = AssistantData(**assistant_data_model_dict) + + # Verify the model instances are equivalent + assert assistant_data_model == assistant_data_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_data_model_json2 = assistant_data_model.to_dict() + assert assistant_data_model_json2 == assistant_data_model_json + +class TestModel_AssistantSkill(): + """ + Test Class for AssistantSkill + """ + + def test_assistant_skill_serialization(self): + """ + Test serialization/deserialization for AssistantSkill + """ + + # Construct a json representation of a AssistantSkill model + assistant_skill_model_json = {} + assistant_skill_model_json['skill_id'] = 'testString' + assistant_skill_model_json['type'] = 'dialog' + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model = AssistantSkill.from_dict(assistant_skill_model_json) + assert assistant_skill_model != False + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model_dict = AssistantSkill.from_dict(assistant_skill_model_json).__dict__ + assistant_skill_model2 = AssistantSkill(**assistant_skill_model_dict) + + # Verify the model instances are equivalent + assert assistant_skill_model == assistant_skill_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_skill_model_json2 = assistant_skill_model.to_dict() + assert assistant_skill_model_json2 == assistant_skill_model_json + +class TestModel_AssistantState(): + """ + Test Class for AssistantState + """ + + def test_assistant_state_serialization(self): + """ + Test serialization/deserialization for AssistantState + """ + + # Construct a json representation of a AssistantState model + assistant_state_model_json = {} + assistant_state_model_json['action_disabled'] = True + assistant_state_model_json['dialog_disabled'] = True + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model = AssistantState.from_dict(assistant_state_model_json) + assert assistant_state_model != False + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model_dict = AssistantState.from_dict(assistant_state_model_json).__dict__ + assistant_state_model2 = AssistantState(**assistant_state_model_dict) + + # Verify the model instances are equivalent + assert assistant_state_model == assistant_state_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_state_model_json2 = assistant_state_model.to_dict() + assert assistant_state_model_json2 == assistant_state_model_json + +class TestModel_BaseEnvironmentOrchestration(): + """ + Test Class for BaseEnvironmentOrchestration + """ + + def test_base_environment_orchestration_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentOrchestration + """ + + # Construct a json representation of a BaseEnvironmentOrchestration model + base_environment_orchestration_model_json = {} + base_environment_orchestration_model_json['search_skill_fallback'] = True + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json) + assert base_environment_orchestration_model != False + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model_dict = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json).__dict__ + base_environment_orchestration_model2 = BaseEnvironmentOrchestration(**base_environment_orchestration_model_dict) + + # Verify the model instances are equivalent + assert base_environment_orchestration_model == base_environment_orchestration_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() + assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json + +class TestModel_BaseEnvironmentReleaseReference(): + """ + Test Class for BaseEnvironmentReleaseReference + """ + + def test_base_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentReleaseReference + """ + + # Construct a json representation of a BaseEnvironmentReleaseReference model + base_environment_release_reference_model_json = {} + base_environment_release_reference_model_json['release'] = 'testString' + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json) + assert base_environment_release_reference_model != False + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model_dict = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json).__dict__ + base_environment_release_reference_model2 = BaseEnvironmentReleaseReference(**base_environment_release_reference_model_dict) + + # Verify the model instances are equivalent + assert base_environment_release_reference_model == base_environment_release_reference_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() + assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json + +class TestModel_BulkClassifyOutput(): + """ + Test Class for BulkClassifyOutput + """ + + def test_bulk_classify_output_serialization(self): + """ + Test serialization/deserialization for BulkClassifyOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + # Construct a json representation of a BulkClassifyOutput model + bulk_classify_output_model_json = {} + bulk_classify_output_model_json['input'] = bulk_classify_utterance_model + bulk_classify_output_model_json['entities'] = [runtime_entity_model] + bulk_classify_output_model_json['intents'] = [runtime_intent_model] + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) + assert bulk_classify_output_model != False + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ + bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_output_model == bulk_classify_output_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() + assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + +class TestModel_BulkClassifyResponse(): + """ + Test Class for BulkClassifyResponse + """ + + def test_bulk_classify_response_serialization(self): + """ + Test serialization/deserialization for BulkClassifyResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model['input'] = bulk_classify_utterance_model + bulk_classify_output_model['entities'] = [runtime_entity_model] + bulk_classify_output_model['intents'] = [runtime_intent_model] + + # Construct a json representation of a BulkClassifyResponse model + bulk_classify_response_model_json = {} + bulk_classify_response_model_json['output'] = [bulk_classify_output_model] + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) + assert bulk_classify_response_model != False + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ + bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_response_model == bulk_classify_response_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() + assert bulk_classify_response_model_json2 == bulk_classify_response_model_json + +class TestModel_BulkClassifyUtterance(): + """ + Test Class for BulkClassifyUtterance + """ + + def test_bulk_classify_utterance_serialization(self): + """ + Test serialization/deserialization for BulkClassifyUtterance + """ + + # Construct a json representation of a BulkClassifyUtterance model + bulk_classify_utterance_model_json = {} + bulk_classify_utterance_model_json['text'] = 'testString' + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) + assert bulk_classify_utterance_model != False + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ + bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() + assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + +class TestModel_CaptureGroup(): + """ + Test Class for CaptureGroup + """ + + def test_capture_group_serialization(self): + """ + Test serialization/deserialization for CaptureGroup + """ + + # Construct a json representation of a CaptureGroup model + capture_group_model_json = {} + capture_group_model_json['group'] = 'testString' + capture_group_model_json['location'] = [38] + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model = CaptureGroup.from_dict(capture_group_model_json) + assert capture_group_model != False + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ + capture_group_model2 = CaptureGroup(**capture_group_model_dict) + + # Verify the model instances are equivalent + assert capture_group_model == capture_group_model2 + + # Convert model instance back to dict and verify no loss of data + capture_group_model_json2 = capture_group_model.to_dict() + assert capture_group_model_json2 == capture_group_model_json + +class TestModel_ChannelTransferInfo(): + """ + Test Class for ChannelTransferInfo + """ + + def test_channel_transfer_info_serialization(self): + """ + Test serialization/deserialization for ChannelTransferInfo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a json representation of a ChannelTransferInfo model + channel_transfer_info_model_json = {} + channel_transfer_info_model_json['target'] = channel_transfer_target_model + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) + assert channel_transfer_info_model != False + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ + channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_info_model == channel_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() + assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + +class TestModel_ChannelTransferTarget(): + """ + Test Class for ChannelTransferTarget + """ + + def test_channel_transfer_target_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTarget + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a json representation of a ChannelTransferTarget model + channel_transfer_target_model_json = {} + channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) + assert channel_transfer_target_model != False + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ + channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_model == channel_transfer_target_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() + assert channel_transfer_target_model_json2 == channel_transfer_target_model_json + +class TestModel_ChannelTransferTargetChat(): + """ + Test Class for ChannelTransferTargetChat + """ + + def test_channel_transfer_target_chat_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTargetChat + """ + + # Construct a json representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model_json = {} + channel_transfer_target_chat_model_json['url'] = 'testString' + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) + assert channel_transfer_target_chat_model != False + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation channel_transfer_target_chat_model_dict = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json).__dict__ channel_transfer_target_chat_model2 = ChannelTransferTargetChat(**channel_transfer_target_chat_model_dict) # Verify the model instances are equivalent - assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() + assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + +class TestModel_DialogLogMessage(): + """ + Test Class for DialogLogMessage + """ + + def test_dialog_log_message_serialization(self): + """ + Test serialization/deserialization for DialogLogMessage + """ + + # Construct dict forms of any model objects needed in order to build this model. + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + # Construct a json representation of a DialogLogMessage model + dialog_log_message_model_json = {} + dialog_log_message_model_json['level'] = 'info' + dialog_log_message_model_json['message'] = 'testString' + dialog_log_message_model_json['code'] = 'testString' + dialog_log_message_model_json['source'] = log_message_source_model + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) + assert dialog_log_message_model != False + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model_dict = DialogLogMessage.from_dict(dialog_log_message_model_json).__dict__ + dialog_log_message_model2 = DialogLogMessage(**dialog_log_message_model_dict) + + # Verify the model instances are equivalent + assert dialog_log_message_model == dialog_log_message_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_log_message_model_json2 = dialog_log_message_model.to_dict() + assert dialog_log_message_model_json2 == dialog_log_message_model_json + +class TestModel_DialogNodeAction(): + """ + Test Class for DialogNodeAction + """ + + def test_dialog_node_action_serialization(self): + """ + Test serialization/deserialization for DialogNodeAction + """ + + # Construct a json representation of a DialogNodeAction model + dialog_node_action_model_json = {} + dialog_node_action_model_json['name'] = 'testString' + dialog_node_action_model_json['type'] = 'client' + dialog_node_action_model_json['parameters'] = {'foo': 'bar'} + dialog_node_action_model_json['result_variable'] = 'testString' + dialog_node_action_model_json['credentials'] = 'testString' + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) + assert dialog_node_action_model != False + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ + dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_action_model == dialog_node_action_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_action_model_json2 = dialog_node_action_model.to_dict() + assert dialog_node_action_model_json2 == dialog_node_action_model_json + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): + """ + Test Class for DialogNodeOutputConnectToAgentTransferInfo + """ + + def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + """ + + # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model + dialog_node_output_connect_to_agent_transfer_info_model_json = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) + assert dialog_node_output_connect_to_agent_transfer_info_model != False + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ + dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() + assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + +class TestModel_DialogNodeOutputOptionsElement(): + """ + Test Class for DialogNodeOutputOptionsElement + """ + + def test_dialog_node_output_options_element_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElement + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + # Construct a json representation of a DialogNodeOutputOptionsElement model + dialog_node_output_options_element_model_json = {} + dialog_node_output_options_element_model_json['label'] = 'testString' + dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) + assert dialog_node_output_options_element_model != False + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ + dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() + assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json + +class TestModel_DialogNodeOutputOptionsElementValue(): + """ + Test Class for DialogNodeOutputOptionsElementValue + """ + + def test_dialog_node_output_options_element_value_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElementValue + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a DialogNodeOutputOptionsElementValue model + dialog_node_output_options_element_value_model_json = {} + dialog_node_output_options_element_value_model_json['input'] = message_input_model + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) + assert dialog_node_output_options_element_value_model != False + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ + dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() + assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json + +class TestModel_DialogNodeVisited(): + """ + Test Class for DialogNodeVisited + """ + + def test_dialog_node_visited_serialization(self): + """ + Test serialization/deserialization for DialogNodeVisited + """ + + # Construct a json representation of a DialogNodeVisited model + dialog_node_visited_model_json = {} + dialog_node_visited_model_json['dialog_node'] = 'testString' + dialog_node_visited_model_json['title'] = 'testString' + dialog_node_visited_model_json['conditions'] = 'testString' + + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model = DialogNodeVisited.from_dict(dialog_node_visited_model_json) + assert dialog_node_visited_model != False + + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model_dict = DialogNodeVisited.from_dict(dialog_node_visited_model_json).__dict__ + dialog_node_visited_model2 = DialogNodeVisited(**dialog_node_visited_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_visited_model == dialog_node_visited_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() + assert dialog_node_visited_model_json2 == dialog_node_visited_model_json + +class TestModel_DialogSuggestion(): + """ + Test Class for DialogSuggestion + """ + + def test_dialog_suggestion_serialization(self): + """ + Test serialization/deserialization for DialogSuggestion + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model['input'] = message_input_model + + # Construct a json representation of a DialogSuggestion model + dialog_suggestion_model_json = {} + dialog_suggestion_model_json['label'] = 'testString' + dialog_suggestion_model_json['value'] = dialog_suggestion_value_model + dialog_suggestion_model_json['output'] = {'foo': 'bar'} + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) + assert dialog_suggestion_model != False + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ + dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) + + # Verify the model instances are equivalent + assert dialog_suggestion_model == dialog_suggestion_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() + assert dialog_suggestion_model_json2 == dialog_suggestion_model_json + +class TestModel_DialogSuggestionValue(): + """ + Test Class for DialogSuggestionValue + """ + + def test_dialog_suggestion_value_serialization(self): + """ + Test serialization/deserialization for DialogSuggestionValue + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a DialogSuggestionValue model + dialog_suggestion_value_model_json = {} + dialog_suggestion_value_model_json['input'] = message_input_model + + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) + assert dialog_suggestion_value_model != False + + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ + dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) + + # Verify the model instances are equivalent + assert dialog_suggestion_value_model == dialog_suggestion_value_model2 # Convert model instance back to dict and verify no loss of data - channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() - assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() + assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_DialogLogMessage(): +class TestModel_Environment(): """ - Test Class for DialogLogMessage + Test Class for Environment """ - def test_dialog_log_message_serialization(self): + def test_environment_serialization(self): """ - Test serialization/deserialization for DialogLogMessage + Test serialization/deserialization for Environment """ # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' - # Construct a json representation of a DialogLogMessage model - dialog_log_message_model_json = {} - dialog_log_message_model_json['level'] = 'info' - dialog_log_message_model_json['message'] = 'testString' - dialog_log_message_model_json['code'] = 'testString' - dialog_log_message_model_json['source'] = log_message_source_model + # Construct a json representation of a Environment model + environment_model_json = {} + environment_model_json['name'] = 'testString' + environment_model_json['description'] = 'testString' + environment_model_json['session_timeout'] = 10 + environment_model_json['skill_references'] = [environment_skill_model] - # Construct a model instance of DialogLogMessage by calling from_dict on the json representation - dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) - assert dialog_log_message_model != False + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model = Environment.from_dict(environment_model_json) + assert environment_model != False - # Construct a model instance of DialogLogMessage by calling from_dict on the json representation - dialog_log_message_model_dict = DialogLogMessage.from_dict(dialog_log_message_model_json).__dict__ - dialog_log_message_model2 = DialogLogMessage(**dialog_log_message_model_dict) + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model_dict = Environment.from_dict(environment_model_json).__dict__ + environment_model2 = Environment(**environment_model_dict) # Verify the model instances are equivalent - assert dialog_log_message_model == dialog_log_message_model2 + assert environment_model == environment_model2 # Convert model instance back to dict and verify no loss of data - dialog_log_message_model_json2 = dialog_log_message_model.to_dict() - assert dialog_log_message_model_json2 == dialog_log_message_model_json + environment_model_json2 = environment_model.to_dict() + assert environment_model_json2 == environment_model_json -class TestModel_DialogNodeAction(): +class TestModel_EnvironmentCollection(): """ - Test Class for DialogNodeAction + Test Class for EnvironmentCollection """ - def test_dialog_node_action_serialization(self): + def test_environment_collection_serialization(self): """ - Test serialization/deserialization for DialogNodeAction + Test serialization/deserialization for EnvironmentCollection """ - # Construct a json representation of a DialogNodeAction model - dialog_node_action_model_json = {} - dialog_node_action_model_json['name'] = 'testString' - dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {} - dialog_node_action_model_json['result_variable'] = 'testString' - dialog_node_action_model_json['credentials'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of DialogNodeAction by calling from_dict on the json representation - dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) - assert dialog_node_action_model != False + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' + + environment_model = {} # Environment + environment_model['name'] = 'testString' + environment_model['description'] = 'testString' + environment_model['session_timeout'] = 10 + environment_model['skill_references'] = [environment_skill_model] + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a EnvironmentCollection model + environment_collection_model_json = {} + environment_collection_model_json['environments'] = [environment_model] + environment_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model = EnvironmentCollection.from_dict(environment_collection_model_json) + assert environment_collection_model != False + + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model_dict = EnvironmentCollection.from_dict(environment_collection_model_json).__dict__ + environment_collection_model2 = EnvironmentCollection(**environment_collection_model_dict) - # Construct a model instance of DialogNodeAction by calling from_dict on the json representation - dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ - dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + # Verify the model instances are equivalent + assert environment_collection_model == environment_collection_model2 + + # Convert model instance back to dict and verify no loss of data + environment_collection_model_json2 = environment_collection_model.to_dict() + assert environment_collection_model_json2 == environment_collection_model_json + +class TestModel_EnvironmentReference(): + """ + Test Class for EnvironmentReference + """ + + def test_environment_reference_serialization(self): + """ + Test serialization/deserialization for EnvironmentReference + """ + + # Construct a json representation of a EnvironmentReference model + environment_reference_model_json = {} + environment_reference_model_json['name'] = 'testString' + + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model = EnvironmentReference.from_dict(environment_reference_model_json) + assert environment_reference_model != False + + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model_dict = EnvironmentReference.from_dict(environment_reference_model_json).__dict__ + environment_reference_model2 = EnvironmentReference(**environment_reference_model_dict) # Verify the model instances are equivalent - assert dialog_node_action_model == dialog_node_action_model2 + assert environment_reference_model == environment_reference_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_action_model_json2 = dialog_node_action_model.to_dict() - assert dialog_node_action_model_json2 == dialog_node_action_model_json + environment_reference_model_json2 = environment_reference_model.to_dict() + assert environment_reference_model_json2 == environment_reference_model_json -class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): +class TestModel_EnvironmentSkill(): """ - Test Class for DialogNodeOutputConnectToAgentTransferInfo + Test Class for EnvironmentSkill """ - def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): + def test_environment_skill_serialization(self): """ - Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + Test serialization/deserialization for EnvironmentSkill """ - # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model - dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {} + # Construct a json representation of a EnvironmentSkill model + environment_skill_model_json = {} + environment_skill_model_json['skill_id'] = 'testString' + environment_skill_model_json['type'] = 'dialog' + environment_skill_model_json['disabled'] = True + environment_skill_model_json['snapshot'] = 'testString' + environment_skill_model_json['skill_reference'] = 'testString' - # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation - dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) - assert dialog_node_output_connect_to_agent_transfer_info_model != False + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model = EnvironmentSkill.from_dict(environment_skill_model_json) + assert environment_skill_model != False - # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation - dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ - dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model_dict = EnvironmentSkill.from_dict(environment_skill_model_json).__dict__ + environment_skill_model2 = EnvironmentSkill(**environment_skill_model_dict) # Verify the model instances are equivalent - assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + assert environment_skill_model == environment_skill_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() - assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + environment_skill_model_json2 = environment_skill_model.to_dict() + assert environment_skill_model_json2 == environment_skill_model_json -class TestModel_DialogNodeOutputOptionsElement(): +class TestModel_IntegrationReference(): """ - Test Class for DialogNodeOutputOptionsElement + Test Class for IntegrationReference """ - def test_dialog_node_output_options_element_serialization(self): + def test_integration_reference_serialization(self): """ - Test serialization/deserialization for DialogNodeOutputOptionsElement + Test serialization/deserialization for IntegrationReference + """ + + # Construct a json representation of a IntegrationReference model + integration_reference_model_json = {} + integration_reference_model_json['integration_id'] = 'testString' + integration_reference_model_json['type'] = 'testString' + + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) + assert integration_reference_model != False + + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ + integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) + + # Verify the model instances are equivalent + assert integration_reference_model == integration_reference_model2 + + # Convert model instance back to dict and verify no loss of data + integration_reference_model_json2 = integration_reference_model.to_dict() + assert integration_reference_model_json2 == integration_reference_model_json + +class TestModel_Log(): + """ + Test Class for Log + """ + + def test_log_serialization(self): + """ + Test serialization/deserialization for Log """ # Construct dict forms of any model objects needed in order to build this model. @@ -1571,6 +4567,7 @@ def test_dialog_node_output_options_element_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -1620,11 +4617,17 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -1644,39 +4647,157 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a json representation of a DialogNodeOutputOptionsElement model - dialog_node_output_options_element_model_json = {} - dialog_node_output_options_element_model_json['label'] = 'testString' - dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'foo': 'bar'} + + message_request_model = {} # MessageRequest + message_request_model['input'] = message_input_model + message_request_model['context'] = message_context_model + message_request_model['user_id'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['spelling'] = message_output_spelling_model + + message_response_model = {} # MessageResponse + message_response_model['output'] = message_output_model + message_response_model['context'] = message_context_model + message_response_model['user_id'] = 'testString' + + # Construct a json representation of a Log model + log_model_json = {} + log_model_json['log_id'] = 'testString' + log_model_json['request'] = message_request_model + log_model_json['response'] = message_response_model + log_model_json['assistant_id'] = 'testString' + log_model_json['session_id'] = 'testString' + log_model_json['skill_id'] = 'testString' + log_model_json['snapshot'] = 'testString' + log_model_json['request_timestamp'] = 'testString' + log_model_json['response_timestamp'] = 'testString' + log_model_json['language'] = 'testString' + log_model_json['customer_id'] = 'testString' - # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation - dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) - assert dialog_node_output_options_element_model != False + # Construct a model instance of Log by calling from_dict on the json representation + log_model = Log.from_dict(log_model_json) + assert log_model != False - # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation - dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ - dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) + # Construct a model instance of Log by calling from_dict on the json representation + log_model_dict = Log.from_dict(log_model_json).__dict__ + log_model2 = Log(**log_model_dict) # Verify the model instances are equivalent - assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 + assert log_model == log_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() - assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json + log_model_json2 = log_model.to_dict() + assert log_model_json2 == log_model_json -class TestModel_DialogNodeOutputOptionsElementValue(): +class TestModel_LogCollection(): """ - Test Class for DialogNodeOutputOptionsElementValue + Test Class for LogCollection """ - def test_dialog_node_output_options_element_value_serialization(self): + def test_log_collection_serialization(self): """ - Test serialization/deserialization for DialogNodeOutputOptionsElementValue + Test serialization/deserialization for LogCollection """ # Construct dict forms of any model objects needed in order to build this model. @@ -1684,6 +4805,7 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -1733,11 +4855,17 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -1757,370 +4885,543 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - # Construct a json representation of a DialogNodeOutputOptionsElementValue model - dialog_node_output_options_element_value_model_json = {} - dialog_node_output_options_element_value_model_json['input'] = message_input_model + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'foo': 'bar'} + + message_request_model = {} # MessageRequest + message_request_model['input'] = message_input_model + message_request_model['context'] = message_context_model + message_request_model['user_id'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['spelling'] = message_output_spelling_model + + message_response_model = {} # MessageResponse + message_response_model['output'] = message_output_model + message_response_model['context'] = message_context_model + message_response_model['user_id'] = 'testString' + + log_model = {} # Log + log_model['log_id'] = 'testString' + log_model['request'] = message_request_model + log_model['response'] = message_response_model + log_model['assistant_id'] = 'testString' + log_model['session_id'] = 'testString' + log_model['skill_id'] = 'testString' + log_model['snapshot'] = 'testString' + log_model['request_timestamp'] = 'testString' + log_model['response_timestamp'] = 'testString' + log_model['language'] = 'testString' + log_model['customer_id'] = 'testString' + + log_pagination_model = {} # LogPagination + log_pagination_model['next_url'] = 'testString' + log_pagination_model['matched'] = 38 + log_pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a LogCollection model + log_collection_model_json = {} + log_collection_model_json['logs'] = [log_model] + log_collection_model_json['pagination'] = log_pagination_model + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model = LogCollection.from_dict(log_collection_model_json) + assert log_collection_model != False + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ + log_collection_model2 = LogCollection(**log_collection_model_dict) + + # Verify the model instances are equivalent + assert log_collection_model == log_collection_model2 + + # Convert model instance back to dict and verify no loss of data + log_collection_model_json2 = log_collection_model.to_dict() + assert log_collection_model_json2 == log_collection_model_json + +class TestModel_LogPagination(): + """ + Test Class for LogPagination + """ + + def test_log_pagination_serialization(self): + """ + Test serialization/deserialization for LogPagination + """ + + # Construct a json representation of a LogPagination model + log_pagination_model_json = {} + log_pagination_model_json['next_url'] = 'testString' + log_pagination_model_json['matched'] = 38 + log_pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model = LogPagination.from_dict(log_pagination_model_json) + assert log_pagination_model != False + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ + log_pagination_model2 = LogPagination(**log_pagination_model_dict) + + # Verify the model instances are equivalent + assert log_pagination_model == log_pagination_model2 + + # Convert model instance back to dict and verify no loss of data + log_pagination_model_json2 = log_pagination_model.to_dict() + assert log_pagination_model_json2 == log_pagination_model_json + +class TestModel_MessageContext(): + """ + Test Class for MessageContext + """ + + def test_message_context_serialization(self): + """ + Test serialization/deserialization for MessageContext + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model + + # Construct a json representation of a MessageContext model + message_context_model_json = {} + message_context_model_json['global'] = message_context_global_model + message_context_model_json['skills'] = message_context_skills_model + message_context_model_json['integrations'] = {'foo': 'bar'} + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model = MessageContext.from_dict(message_context_model_json) + assert message_context_model != False + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ + message_context_model2 = MessageContext(**message_context_model_dict) + + # Verify the model instances are equivalent + assert message_context_model == message_context_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_model_json2 = message_context_model.to_dict() + assert message_context_model_json2 == message_context_model_json + +class TestModel_MessageContextGlobal(): + """ + Test Class for MessageContextGlobal + """ + + def test_message_context_global_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobal + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a json representation of a MessageContextGlobal model + message_context_global_model_json = {} + message_context_global_model_json['system'] = message_context_global_system_model - # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation - dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) - assert dialog_node_output_options_element_value_model != False + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) + assert message_context_global_model != False - # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation - dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ - dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ + message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) # Verify the model instances are equivalent - assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 + assert message_context_global_model == message_context_global_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() - assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json + message_context_global_model_json2 = message_context_global_model.to_dict() + assert message_context_global_model_json2 == message_context_global_model_json -class TestModel_DialogNodeVisited(): +class TestModel_MessageContextGlobalStateless(): """ - Test Class for DialogNodeVisited + Test Class for MessageContextGlobalStateless """ - def test_dialog_node_visited_serialization(self): + def test_message_context_global_stateless_serialization(self): """ - Test serialization/deserialization for DialogNodeVisited + Test serialization/deserialization for MessageContextGlobalStateless """ - # Construct a json representation of a DialogNodeVisited model - dialog_node_visited_model_json = {} - dialog_node_visited_model_json['dialog_node'] = 'testString' - dialog_node_visited_model_json['title'] = 'testString' - dialog_node_visited_model_json['conditions'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation - dialog_node_visited_model = DialogNodeVisited.from_dict(dialog_node_visited_model_json) - assert dialog_node_visited_model != False + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation - dialog_node_visited_model_dict = DialogNodeVisited.from_dict(dialog_node_visited_model_json).__dict__ - dialog_node_visited_model2 = DialogNodeVisited(**dialog_node_visited_model_dict) + # Construct a json representation of a MessageContextGlobalStateless model + message_context_global_stateless_model_json = {} + message_context_global_stateless_model_json['system'] = message_context_global_system_model + message_context_global_stateless_model_json['session_id'] = 'testString' + + # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation + message_context_global_stateless_model = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json) + assert message_context_global_stateless_model != False + + # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation + message_context_global_stateless_model_dict = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json).__dict__ + message_context_global_stateless_model2 = MessageContextGlobalStateless(**message_context_global_stateless_model_dict) # Verify the model instances are equivalent - assert dialog_node_visited_model == dialog_node_visited_model2 + assert message_context_global_stateless_model == message_context_global_stateless_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() - assert dialog_node_visited_model_json2 == dialog_node_visited_model_json + message_context_global_stateless_model_json2 = message_context_global_stateless_model.to_dict() + assert message_context_global_stateless_model_json2 == message_context_global_stateless_model_json -class TestModel_DialogSuggestion(): +class TestModel_MessageContextGlobalSystem(): """ - Test Class for DialogSuggestion + Test Class for MessageContextGlobalSystem """ - def test_dialog_suggestion_serialization(self): + def test_message_context_global_system_serialization(self): """ - Test serialization/deserialization for DialogSuggestion + Test serialization/deserialization for MessageContextGlobalSystem """ - # Construct dict forms of any model objects needed in order to build this model. - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a json representation of a MessageContextGlobalSystem model + message_context_global_system_model_json = {} + message_context_global_system_model_json['timezone'] = 'testString' + message_context_global_system_model_json['user_id'] = 'testString' + message_context_global_system_model_json['turn_count'] = 38 + message_context_global_system_model_json['locale'] = 'en-us' + message_context_global_system_model_json['reference_time'] = 'testString' + message_context_global_system_model_json['session_start_time'] = 'testString' + message_context_global_system_model_json['state'] = 'testString' + message_context_global_system_model_json['skip_user_input'] = True - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) + assert message_context_global_system_model != False - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ + message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + # Verify the model instances are equivalent + assert message_context_global_system_model == message_context_global_system_model2 - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_context_global_system_model_json2 = message_context_global_system_model.to_dict() + assert message_context_global_system_model_json2 == message_context_global_system_model_json - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True +class TestModel_MessageContextSkillAction(): + """ + Test Class for MessageContextSkillAction + """ - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + def test_message_context_skill_action_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillAction + """ - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model + # Construct dict forms of any model objects needed in order to build this model. - dialog_suggestion_value_model = {} # DialogSuggestionValue - dialog_suggestion_value_model['input'] = message_input_model + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a json representation of a DialogSuggestion model - dialog_suggestion_model_json = {} - dialog_suggestion_model_json['label'] = 'testString' - dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {} + # Construct a json representation of a MessageContextSkillAction model + message_context_skill_action_model_json = {} + message_context_skill_action_model_json['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model_json['system'] = message_context_skill_system_model + message_context_skill_action_model_json['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model_json['skill_variables'] = {'foo': 'bar'} - # Construct a model instance of DialogSuggestion by calling from_dict on the json representation - dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) - assert dialog_suggestion_model != False + # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation + message_context_skill_action_model = MessageContextSkillAction.from_dict(message_context_skill_action_model_json) + assert message_context_skill_action_model != False - # Construct a model instance of DialogSuggestion by calling from_dict on the json representation - dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ - dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) + # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation + message_context_skill_action_model_dict = MessageContextSkillAction.from_dict(message_context_skill_action_model_json).__dict__ + message_context_skill_action_model2 = MessageContextSkillAction(**message_context_skill_action_model_dict) # Verify the model instances are equivalent - assert dialog_suggestion_model == dialog_suggestion_model2 + assert message_context_skill_action_model == message_context_skill_action_model2 # Convert model instance back to dict and verify no loss of data - dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() - assert dialog_suggestion_model_json2 == dialog_suggestion_model_json + message_context_skill_action_model_json2 = message_context_skill_action_model.to_dict() + assert message_context_skill_action_model_json2 == message_context_skill_action_model_json -class TestModel_DialogSuggestionValue(): +class TestModel_MessageContextSkillDialog(): """ - Test Class for DialogSuggestionValue + Test Class for MessageContextSkillDialog """ - def test_dialog_suggestion_value_serialization(self): + def test_message_context_skill_dialog_serialization(self): """ - Test serialization/deserialization for DialogSuggestionValue + Test serialization/deserialization for MessageContextSkillDialog """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Construct a json representation of a MessageContextSkillDialog model + message_context_skill_dialog_model_json = {} + message_context_skill_dialog_model_json['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model_json['system'] = message_context_skill_system_model - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation + message_context_skill_dialog_model = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json) + assert message_context_skill_dialog_model != False - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation + message_context_skill_dialog_model_dict = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json).__dict__ + message_context_skill_dialog_model2 = MessageContextSkillDialog(**message_context_skill_dialog_model_dict) - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model + # Verify the model instances are equivalent + assert message_context_skill_dialog_model == message_context_skill_dialog_model2 - # Construct a json representation of a DialogSuggestionValue model - dialog_suggestion_value_model_json = {} - dialog_suggestion_value_model_json['input'] = message_input_model + # Convert model instance back to dict and verify no loss of data + message_context_skill_dialog_model_json2 = message_context_skill_dialog_model.to_dict() + assert message_context_skill_dialog_model_json2 == message_context_skill_dialog_model_json - # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation - dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) - assert dialog_suggestion_value_model != False +class TestModel_MessageContextSkillSystem(): + """ + Test Class for MessageContextSkillSystem + """ - # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation - dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ - dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) + def test_message_context_skill_system_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillSystem + """ + + # Construct a json representation of a MessageContextSkillSystem model + message_context_skill_system_model_json = {} + message_context_skill_system_model_json['state'] = 'testString' + message_context_skill_system_model_json['foo'] = 'testString' + + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) + assert message_context_skill_system_model != False + + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ + message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) # Verify the model instances are equivalent - assert dialog_suggestion_value_model == dialog_suggestion_value_model2 + assert message_context_skill_system_model == message_context_skill_system_model2 # Convert model instance back to dict and verify no loss of data - dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() - assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json + message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() + assert message_context_skill_system_model_json2 == message_context_skill_system_model_json -class TestModel_Log(): + # Test get_properties and set_properties methods. + message_context_skill_system_model.set_properties({}) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + message_context_skill_system_model.set_properties(expected_dict) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_MessageContextSkills(): """ - Test Class for Log + Test Class for MessageContextSkills """ - def test_log_serialization(self): + def test_message_context_skills_serialization(self): """ - Test serialization/deserialization for Log + Test serialization/deserialization for MessageContextSkills """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a json representation of a MessageContextSkills model + message_context_skills_model_json = {} + message_context_skills_model_json['main skill'] = message_context_skill_dialog_model + message_context_skills_model_json['actions skill'] = message_context_skill_action_model - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) + assert message_context_skills_model != False - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ + message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Verify the model instances are equivalent + assert message_context_skills_model == message_context_skills_model2 - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + # Convert model instance back to dict and verify no loss of data + message_context_skills_model_json2 = message_context_skills_model.to_dict() + assert message_context_skills_model_json2 == message_context_skills_model_json - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False +class TestModel_MessageContextStateless(): + """ + Test Class for MessageContextStateless + """ - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model + def test_message_context_stateless_serialization(self): + """ + Test serialization/deserialization for MessageContextStateless + """ + + # Construct dict forms of any model objects needed in order to build this model. message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -2132,130 +5433,57 @@ def test_log_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' + message_context_global_stateless_model = {} # MessageContextGlobalStateless + message_context_global_stateless_model['system'] = message_context_global_system_model + message_context_global_stateless_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model - - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } - - message_request_model = {} # MessageRequest - message_request_model['input'] = message_input_model - message_request_model['context'] = message_context_model - message_request_model['user_id'] = 'testString' - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] - - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' - - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' - - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model - - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} - message_output_model['spelling'] = message_output_spelling_model + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} - message_response_model = {} # MessageResponse - message_response_model['output'] = message_output_model - message_response_model['context'] = message_context_model - message_response_model['user_id'] = 'testString' + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model - # Construct a json representation of a Log model - log_model_json = {} - log_model_json['log_id'] = 'testString' - log_model_json['request'] = message_request_model - log_model_json['response'] = message_response_model - log_model_json['assistant_id'] = 'testString' - log_model_json['session_id'] = 'testString' - log_model_json['skill_id'] = 'testString' - log_model_json['snapshot'] = 'testString' - log_model_json['request_timestamp'] = 'testString' - log_model_json['response_timestamp'] = 'testString' - log_model_json['language'] = 'testString' - log_model_json['customer_id'] = 'testString' + # Construct a json representation of a MessageContextStateless model + message_context_stateless_model_json = {} + message_context_stateless_model_json['global'] = message_context_global_stateless_model + message_context_stateless_model_json['skills'] = message_context_skills_model + message_context_stateless_model_json['integrations'] = {'foo': 'bar'} - # Construct a model instance of Log by calling from_dict on the json representation - log_model = Log.from_dict(log_model_json) - assert log_model != False + # Construct a model instance of MessageContextStateless by calling from_dict on the json representation + message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) + assert message_context_stateless_model != False - # Construct a model instance of Log by calling from_dict on the json representation - log_model_dict = Log.from_dict(log_model_json).__dict__ - log_model2 = Log(**log_model_dict) + # Construct a model instance of MessageContextStateless by calling from_dict on the json representation + message_context_stateless_model_dict = MessageContextStateless.from_dict(message_context_stateless_model_json).__dict__ + message_context_stateless_model2 = MessageContextStateless(**message_context_stateless_model_dict) # Verify the model instances are equivalent - assert log_model == log_model2 + assert message_context_stateless_model == message_context_stateless_model2 # Convert model instance back to dict and verify no loss of data - log_model_json2 = log_model.to_dict() - assert log_model_json2 == log_model_json + message_context_stateless_model_json2 = message_context_stateless_model.to_dict() + assert message_context_stateless_model_json2 == message_context_stateless_model_json -class TestModel_LogCollection(): +class TestModel_MessageInput(): """ - Test Class for LogCollection + Test Class for MessageInput """ - def test_log_collection_serialization(self): + def test_message_input_serialization(self): """ - Test serialization/deserialization for LogCollection + Test serialization/deserialization for MessageInput """ # Construct dict forms of any model objects needed in order to build this model. @@ -2263,6 +5491,7 @@ def test_log_collection_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -2312,11 +5541,17 @@ def test_log_collection_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2329,502 +5564,306 @@ def test_log_collection_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model - - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } - - message_request_model = {} # MessageRequest - message_request_model['input'] = message_input_model - message_request_model['context'] = message_context_model - message_request_model['user_id'] = 'testString' - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] - - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' - - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' - - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model - - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' - - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} - message_output_model['spelling'] = message_output_spelling_model - - message_response_model = {} # MessageResponse - message_response_model['output'] = message_output_model - message_response_model['context'] = message_context_model - message_response_model['user_id'] = 'testString' - - log_model = {} # Log - log_model['log_id'] = 'testString' - log_model['request'] = message_request_model - log_model['response'] = message_response_model - log_model['assistant_id'] = 'testString' - log_model['session_id'] = 'testString' - log_model['skill_id'] = 'testString' - log_model['snapshot'] = 'testString' - log_model['request_timestamp'] = 'testString' - log_model['response_timestamp'] = 'testString' - log_model['language'] = 'testString' - log_model['customer_id'] = 'testString' - - log_pagination_model = {} # LogPagination - log_pagination_model['next_url'] = 'testString' - log_pagination_model['matched'] = 38 - log_pagination_model['next_cursor'] = 'testString' - - # Construct a json representation of a LogCollection model - log_collection_model_json = {} - log_collection_model_json['logs'] = [log_model] - log_collection_model_json['pagination'] = log_pagination_model - - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model = LogCollection.from_dict(log_collection_model_json) - assert log_collection_model != False - - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ - log_collection_model2 = LogCollection(**log_collection_model_dict) - - # Verify the model instances are equivalent - assert log_collection_model == log_collection_model2 - - # Convert model instance back to dict and verify no loss of data - log_collection_model_json2 = log_collection_model.to_dict() - assert log_collection_model_json2 == log_collection_model_json - -class TestModel_LogPagination(): - """ - Test Class for LogPagination - """ - - def test_log_pagination_serialization(self): - """ - Test serialization/deserialization for LogPagination - """ - - # Construct a json representation of a LogPagination model - log_pagination_model_json = {} - log_pagination_model_json['next_url'] = 'testString' - log_pagination_model_json['matched'] = 38 - log_pagination_model_json['next_cursor'] = 'testString' - - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model = LogPagination.from_dict(log_pagination_model_json) - assert log_pagination_model != False - - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ - log_pagination_model2 = LogPagination(**log_pagination_model_dict) - - # Verify the model instances are equivalent - assert log_pagination_model == log_pagination_model2 - - # Convert model instance back to dict and verify no loss of data - log_pagination_model_json2 = log_pagination_model.to_dict() - assert log_pagination_model_json2 == log_pagination_model_json - -class TestModel_MessageContext(): - """ - Test Class for MessageContext - """ - - def test_message_context_serialization(self): - """ - Test serialization/deserialization for MessageContext - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model - - # Construct a json representation of a MessageContext model - message_context_model_json = {} - message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = {} - message_context_model_json['integrations'] = { 'foo': 'bar' } + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['message_type'] = 'text' + message_input_model_json['text'] = 'testString' + message_input_model_json['intents'] = [runtime_intent_model] + message_input_model_json['entities'] = [runtime_entity_model] + message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['attachments'] = [message_input_attachment_model] + message_input_model_json['analytics'] = request_analytics_model + message_input_model_json['options'] = message_input_options_model - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model = MessageContext.from_dict(message_context_model_json) - assert message_context_model != False + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ - message_context_model2 = MessageContext(**message_context_model_dict) + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) # Verify the model instances are equivalent - assert message_context_model == message_context_model2 + assert message_input_model == message_input_model2 # Convert model instance back to dict and verify no loss of data - message_context_model_json2 = message_context_model.to_dict() - assert message_context_model_json2 == message_context_model_json - -class TestModel_MessageContextGlobal(): - """ - Test Class for MessageContextGlobal - """ - - def test_message_context_global_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobal - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json - # Construct a json representation of a MessageContextGlobal model - message_context_global_model_json = {} - message_context_global_model_json['system'] = message_context_global_system_model - message_context_global_model_json['session_id'] = 'testString' +class TestModel_MessageInputAttachment(): + """ + Test Class for MessageInputAttachment + """ - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) - assert message_context_global_model != False + def test_message_input_attachment_serialization(self): + """ + Test serialization/deserialization for MessageInputAttachment + """ - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ - message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) + # Construct a json representation of a MessageInputAttachment model + message_input_attachment_model_json = {} + message_input_attachment_model_json['url'] = 'testString' + message_input_attachment_model_json['media_type'] = 'testString' + + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) + assert message_input_attachment_model != False + + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ + message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) # Verify the model instances are equivalent - assert message_context_global_model == message_context_global_model2 + assert message_input_attachment_model == message_input_attachment_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_model_json2 = message_context_global_model.to_dict() - assert message_context_global_model_json2 == message_context_global_model_json + message_input_attachment_model_json2 = message_input_attachment_model.to_dict() + assert message_input_attachment_model_json2 == message_input_attachment_model_json -class TestModel_MessageContextGlobalStateless(): +class TestModel_MessageInputOptions(): """ - Test Class for MessageContextGlobalStateless + Test Class for MessageInputOptions """ - def test_message_context_global_stateless_serialization(self): + def test_message_input_options_serialization(self): """ - Test serialization/deserialization for MessageContextGlobalStateless + Test serialization/deserialization for MessageInputOptions """ # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Construct a json representation of a MessageContextGlobalStateless model - message_context_global_stateless_model_json = {} - message_context_global_stateless_model_json['system'] = message_context_global_system_model - message_context_global_stateless_model_json['session_id'] = 'testString' + # Construct a json representation of a MessageInputOptions model + message_input_options_model_json = {} + message_input_options_model_json['restart'] = False + message_input_options_model_json['alternate_intents'] = False + message_input_options_model_json['spelling'] = message_input_options_spelling_model + message_input_options_model_json['debug'] = False + message_input_options_model_json['return_context'] = False + message_input_options_model_json['export'] = False - # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation - message_context_global_stateless_model = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json) - assert message_context_global_stateless_model != False + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) + assert message_input_options_model != False - # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation - message_context_global_stateless_model_dict = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json).__dict__ - message_context_global_stateless_model2 = MessageContextGlobalStateless(**message_context_global_stateless_model_dict) + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ + message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) # Verify the model instances are equivalent - assert message_context_global_stateless_model == message_context_global_stateless_model2 + assert message_input_options_model == message_input_options_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_stateless_model_json2 = message_context_global_stateless_model.to_dict() - assert message_context_global_stateless_model_json2 == message_context_global_stateless_model_json + message_input_options_model_json2 = message_input_options_model.to_dict() + assert message_input_options_model_json2 == message_input_options_model_json -class TestModel_MessageContextGlobalSystem(): +class TestModel_MessageInputOptionsSpelling(): """ - Test Class for MessageContextGlobalSystem + Test Class for MessageInputOptionsSpelling """ - def test_message_context_global_system_serialization(self): + def test_message_input_options_spelling_serialization(self): """ - Test serialization/deserialization for MessageContextGlobalSystem + Test serialization/deserialization for MessageInputOptionsSpelling """ - # Construct a json representation of a MessageContextGlobalSystem model - message_context_global_system_model_json = {} - message_context_global_system_model_json['timezone'] = 'testString' - message_context_global_system_model_json['user_id'] = 'testString' - message_context_global_system_model_json['turn_count'] = 38 - message_context_global_system_model_json['locale'] = 'en-us' - message_context_global_system_model_json['reference_time'] = 'testString' - message_context_global_system_model_json['session_start_time'] = 'testString' - message_context_global_system_model_json['state'] = 'testString' - message_context_global_system_model_json['skip_user_input'] = True + # Construct a json representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model_json = {} + message_input_options_spelling_model_json['suggestions'] = True + message_input_options_spelling_model_json['auto_correct'] = True - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) - assert message_context_global_system_model != False + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) + assert message_input_options_spelling_model != False - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ - message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ + message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) # Verify the model instances are equivalent - assert message_context_global_system_model == message_context_global_system_model2 + assert message_input_options_spelling_model == message_input_options_spelling_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_system_model_json2 = message_context_global_system_model.to_dict() - assert message_context_global_system_model_json2 == message_context_global_system_model_json + message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() + assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json -class TestModel_MessageContextSkill(): +class TestModel_MessageInputOptionsStateless(): """ - Test Class for MessageContextSkill + Test Class for MessageInputOptionsStateless """ - def test_message_context_skill_serialization(self): + def test_message_input_options_stateless_serialization(self): """ - Test serialization/deserialization for MessageContextSkill + Test serialization/deserialization for MessageInputOptionsStateless """ # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Construct a json representation of a MessageContextSkill model - message_context_skill_model_json = {} - message_context_skill_model_json['user_defined'] = {} - message_context_skill_model_json['system'] = message_context_skill_system_model + # Construct a json representation of a MessageInputOptionsStateless model + message_input_options_stateless_model_json = {} + message_input_options_stateless_model_json['restart'] = False + message_input_options_stateless_model_json['alternate_intents'] = False + message_input_options_stateless_model_json['spelling'] = message_input_options_spelling_model + message_input_options_stateless_model_json['debug'] = False - # Construct a model instance of MessageContextSkill by calling from_dict on the json representation - message_context_skill_model = MessageContextSkill.from_dict(message_context_skill_model_json) - assert message_context_skill_model != False + # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation + message_input_options_stateless_model = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json) + assert message_input_options_stateless_model != False - # Construct a model instance of MessageContextSkill by calling from_dict on the json representation - message_context_skill_model_dict = MessageContextSkill.from_dict(message_context_skill_model_json).__dict__ - message_context_skill_model2 = MessageContextSkill(**message_context_skill_model_dict) + # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation + message_input_options_stateless_model_dict = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json).__dict__ + message_input_options_stateless_model2 = MessageInputOptionsStateless(**message_input_options_stateless_model_dict) # Verify the model instances are equivalent - assert message_context_skill_model == message_context_skill_model2 + assert message_input_options_stateless_model == message_input_options_stateless_model2 # Convert model instance back to dict and verify no loss of data - message_context_skill_model_json2 = message_context_skill_model.to_dict() - assert message_context_skill_model_json2 == message_context_skill_model_json + message_input_options_stateless_model_json2 = message_input_options_stateless_model.to_dict() + assert message_input_options_stateless_model_json2 == message_input_options_stateless_model_json -class TestModel_MessageContextSkillSystem(): +class TestModel_MessageInputStateless(): """ - Test Class for MessageContextSkillSystem + Test Class for MessageInputStateless """ - def test_message_context_skill_system_serialization(self): + def test_message_input_stateless_serialization(self): """ - Test serialization/deserialization for MessageContextSkillSystem + Test serialization/deserialization for MessageInputStateless """ - # Construct a json representation of a MessageContextSkillSystem model - message_context_skill_system_model_json = {} - message_context_skill_system_model_json['state'] = 'testString' - message_context_skill_system_model_json['foo'] = 'testString' - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) - assert message_context_skill_system_model != False - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ - message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_system_model == message_context_skill_system_model2 + # Construct dict forms of any model objects needed in order to build this model. - # Convert model instance back to dict and verify no loss of data - message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() - assert message_context_skill_system_model_json2 == message_context_skill_system_model_json + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - # Test get_properties and set_properties methods. - message_context_skill_system_model.set_properties({}) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == {} + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - expected_dict = {'foo': 'testString'} - message_context_skill_system_model.set_properties(expected_dict) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == expected_dict + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' -class TestModel_MessageContextStateless(): - """ - Test Class for MessageContextStateless - """ + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - def test_message_context_stateless_serialization(self): - """ - Test serialization/deserialization for MessageContextStateless - """ + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - # Construct dict forms of any model objects needed in order to build this model. + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - message_context_global_stateless_model = {} # MessageContextGlobalStateless - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model + message_input_options_stateless_model = {} # MessageInputOptionsStateless + message_input_options_stateless_model['restart'] = False + message_input_options_stateless_model['alternate_intents'] = False + message_input_options_stateless_model['spelling'] = message_input_options_spelling_model + message_input_options_stateless_model['debug'] = False - # Construct a json representation of a MessageContextStateless model - message_context_stateless_model_json = {} - message_context_stateless_model_json['global'] = message_context_global_stateless_model - message_context_stateless_model_json['skills'] = {} - message_context_stateless_model_json['integrations'] = { 'foo': 'bar' } + # Construct a json representation of a MessageInputStateless model + message_input_stateless_model_json = {} + message_input_stateless_model_json['message_type'] = 'text' + message_input_stateless_model_json['text'] = 'testString' + message_input_stateless_model_json['intents'] = [runtime_intent_model] + message_input_stateless_model_json['entities'] = [runtime_entity_model] + message_input_stateless_model_json['suggestion_id'] = 'testString' + message_input_stateless_model_json['attachments'] = [message_input_attachment_model] + message_input_stateless_model_json['analytics'] = request_analytics_model + message_input_stateless_model_json['options'] = message_input_options_stateless_model - # Construct a model instance of MessageContextStateless by calling from_dict on the json representation - message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) - assert message_context_stateless_model != False + # Construct a model instance of MessageInputStateless by calling from_dict on the json representation + message_input_stateless_model = MessageInputStateless.from_dict(message_input_stateless_model_json) + assert message_input_stateless_model != False - # Construct a model instance of MessageContextStateless by calling from_dict on the json representation - message_context_stateless_model_dict = MessageContextStateless.from_dict(message_context_stateless_model_json).__dict__ - message_context_stateless_model2 = MessageContextStateless(**message_context_stateless_model_dict) + # Construct a model instance of MessageInputStateless by calling from_dict on the json representation + message_input_stateless_model_dict = MessageInputStateless.from_dict(message_input_stateless_model_json).__dict__ + message_input_stateless_model2 = MessageInputStateless(**message_input_stateless_model_dict) # Verify the model instances are equivalent - assert message_context_stateless_model == message_context_stateless_model2 + assert message_input_stateless_model == message_input_stateless_model2 # Convert model instance back to dict and verify no loss of data - message_context_stateless_model_json2 = message_context_stateless_model.to_dict() - assert message_context_stateless_model_json2 == message_context_stateless_model_json + message_input_stateless_model_json2 = message_input_stateless_model.to_dict() + assert message_input_stateless_model_json2 == message_input_stateless_model_json -class TestModel_MessageInput(): +class TestModel_MessageOutput(): """ - Test Class for MessageInput + Test Class for MessageOutput """ - def test_message_input_serialization(self): + def test_message_output_serialization(self): """ - Test serialization/deserialization for MessageInput + Test serialization/deserialization for MessageOutput """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -2874,194 +5913,184 @@ def test_message_input_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - # Construct a json representation of a MessageInput model - message_input_model_json = {} - message_input_model_json['message_type'] = 'text' - message_input_model_json['text'] = 'testString' - message_input_model_json['intents'] = [runtime_intent_model] - message_input_model_json['entities'] = [runtime_entity_model] - message_input_model_json['suggestion_id'] = 'testString' - message_input_model_json['attachments'] = [message_input_attachment_model] - message_input_model_json['options'] = message_input_options_model + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model = MessageInput.from_dict(message_input_model_json) - assert message_input_model != False + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ - message_input_model2 = MessageInput(**message_input_model_dict) + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model - # Verify the model instances are equivalent - assert message_input_model == message_input_model2 + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Convert model instance back to dict and verify no loss of data - message_input_model_json2 = message_input_model.to_dict() - assert message_input_model_json2 == message_input_model_json + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' -class TestModel_MessageInputAttachment(): - """ - Test Class for MessageInputAttachment - """ + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - def test_message_input_attachment_serialization(self): - """ - Test serialization/deserialization for MessageInputAttachment - """ + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' - # Construct a json representation of a MessageInputAttachment model - message_input_attachment_model_json = {} - message_input_attachment_model_json['url'] = 'testString' - message_input_attachment_model_json['media_type'] = 'testString' + # Construct a json representation of a MessageOutput model + message_output_model_json = {} + message_output_model_json['generic'] = [runtime_response_generic_model] + message_output_model_json['intents'] = [runtime_intent_model] + message_output_model_json['entities'] = [runtime_entity_model] + message_output_model_json['actions'] = [dialog_node_action_model] + message_output_model_json['debug'] = message_output_debug_model + message_output_model_json['user_defined'] = {'foo': 'bar'} + message_output_model_json['spelling'] = message_output_spelling_model - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) - assert message_input_attachment_model != False + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model = MessageOutput.from_dict(message_output_model_json) + assert message_output_model != False - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ - message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ + message_output_model2 = MessageOutput(**message_output_model_dict) # Verify the model instances are equivalent - assert message_input_attachment_model == message_input_attachment_model2 + assert message_output_model == message_output_model2 # Convert model instance back to dict and verify no loss of data - message_input_attachment_model_json2 = message_input_attachment_model.to_dict() - assert message_input_attachment_model_json2 == message_input_attachment_model_json + message_output_model_json2 = message_output_model.to_dict() + assert message_output_model_json2 == message_output_model_json -class TestModel_MessageInputOptions(): +class TestModel_MessageOutputDebug(): """ - Test Class for MessageInputOptions + Test Class for MessageOutputDebug """ - def test_message_input_options_serialization(self): + def test_message_output_debug_serialization(self): """ - Test serialization/deserialization for MessageInputOptions + Test serialization/deserialization for MessageOutputDebug """ # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - # Construct a json representation of a MessageInputOptions model - message_input_options_model_json = {} - message_input_options_model_json['restart'] = False - message_input_options_model_json['alternate_intents'] = False - message_input_options_model_json['spelling'] = message_input_options_spelling_model - message_input_options_model_json['debug'] = False - message_input_options_model_json['return_context'] = False - message_input_options_model_json['export'] = False - - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) - assert message_input_options_model != False - - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ - message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Verify the model instances are equivalent - assert message_input_options_model == message_input_options_model2 + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - # Convert model instance back to dict and verify no loss of data - message_input_options_model_json2 = message_input_options_model.to_dict() - assert message_input_options_model_json2 == message_input_options_model_json + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model -class TestModel_MessageInputOptionsSpelling(): - """ - Test Class for MessageInputOptionsSpelling - """ + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - def test_message_input_options_spelling_serialization(self): - """ - Test serialization/deserialization for MessageInputOptionsSpelling - """ + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' - # Construct a json representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model_json = {} - message_input_options_spelling_model_json['suggestions'] = True - message_input_options_spelling_model_json['auto_correct'] = True + # Construct a json representation of a MessageOutputDebug model + message_output_debug_model_json = {} + message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model_json['log_messages'] = [dialog_log_message_model] + message_output_debug_model_json['branch_exited'] = True + message_output_debug_model_json['branch_exited_reason'] = 'completed' + message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) - assert message_input_options_spelling_model != False + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) + assert message_output_debug_model != False - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ - message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ + message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) # Verify the model instances are equivalent - assert message_input_options_spelling_model == message_input_options_spelling_model2 + assert message_output_debug_model == message_output_debug_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() - assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json + message_output_debug_model_json2 = message_output_debug_model.to_dict() + assert message_output_debug_model_json2 == message_output_debug_model_json -class TestModel_MessageInputOptionsStateless(): +class TestModel_MessageOutputSpelling(): """ - Test Class for MessageInputOptionsStateless + Test Class for MessageOutputSpelling """ - def test_message_input_options_stateless_serialization(self): + def test_message_output_spelling_serialization(self): """ - Test serialization/deserialization for MessageInputOptionsStateless + Test serialization/deserialization for MessageOutputSpelling """ - # Construct dict forms of any model objects needed in order to build this model. - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - # Construct a json representation of a MessageInputOptionsStateless model - message_input_options_stateless_model_json = {} - message_input_options_stateless_model_json['restart'] = False - message_input_options_stateless_model_json['alternate_intents'] = False - message_input_options_stateless_model_json['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model_json['debug'] = False + # Construct a json representation of a MessageOutputSpelling model + message_output_spelling_model_json = {} + message_output_spelling_model_json['text'] = 'testString' + message_output_spelling_model_json['original_text'] = 'testString' + message_output_spelling_model_json['suggested_text'] = 'testString' - # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation - message_input_options_stateless_model = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json) - assert message_input_options_stateless_model != False + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) + assert message_output_spelling_model != False - # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation - message_input_options_stateless_model_dict = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json).__dict__ - message_input_options_stateless_model2 = MessageInputOptionsStateless(**message_input_options_stateless_model_dict) + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ + message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) # Verify the model instances are equivalent - assert message_input_options_stateless_model == message_input_options_stateless_model2 + assert message_output_spelling_model == message_output_spelling_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_stateless_model_json2 = message_input_options_stateless_model.to_dict() - assert message_input_options_stateless_model_json2 == message_input_options_stateless_model_json + message_output_spelling_model_json2 = message_output_spelling_model.to_dict() + assert message_output_spelling_model_json2 == message_output_spelling_model_json -class TestModel_MessageInputStateless(): +class TestModel_MessageRequest(): """ - Test Class for MessageInputStateless + Test Class for MessageRequest """ - def test_message_input_stateless_serialization(self): + def test_message_request_serialization(self): """ - Test serialization/deserialization for MessageInputStateless + Test serialization/deserialization for MessageRequest """ # Construct dict forms of any model objects needed in order to build this model. @@ -3069,6 +6098,7 @@ def test_message_input_stateless_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3118,61 +6148,120 @@ def test_message_input_stateless_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_stateless_model = {} # MessageInputOptionsStateless - message_input_options_stateless_model['restart'] = False - message_input_options_stateless_model['alternate_intents'] = False - message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = False + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True - # Construct a json representation of a MessageInputStateless model - message_input_stateless_model_json = {} - message_input_stateless_model_json['message_type'] = 'text' - message_input_stateless_model_json['text'] = 'testString' - message_input_stateless_model_json['intents'] = [runtime_intent_model] - message_input_stateless_model_json['entities'] = [runtime_entity_model] - message_input_stateless_model_json['suggestion_id'] = 'testString' - message_input_stateless_model_json['attachments'] = [message_input_attachment_model] - message_input_stateless_model_json['options'] = message_input_options_stateless_model + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'Hello' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - # Construct a model instance of MessageInputStateless by calling from_dict on the json representation - message_input_stateless_model = MessageInputStateless.from_dict(message_input_stateless_model_json) - assert message_input_stateless_model != False + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'my_user_id' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of MessageInputStateless by calling from_dict on the json representation - message_input_stateless_model_dict = MessageInputStateless.from_dict(message_input_stateless_model_json).__dict__ - message_input_stateless_model2 = MessageInputStateless(**message_input_stateless_model_dict) + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'foo': 'bar'} + + # Construct a json representation of a MessageRequest model + message_request_model_json = {} + message_request_model_json['input'] = message_input_model + message_request_model_json['context'] = message_context_model + message_request_model_json['user_id'] = 'testString' + + # Construct a model instance of MessageRequest by calling from_dict on the json representation + message_request_model = MessageRequest.from_dict(message_request_model_json) + assert message_request_model != False + + # Construct a model instance of MessageRequest by calling from_dict on the json representation + message_request_model_dict = MessageRequest.from_dict(message_request_model_json).__dict__ + message_request_model2 = MessageRequest(**message_request_model_dict) # Verify the model instances are equivalent - assert message_input_stateless_model == message_input_stateless_model2 + assert message_request_model == message_request_model2 # Convert model instance back to dict and verify no loss of data - message_input_stateless_model_json2 = message_input_stateless_model.to_dict() - assert message_input_stateless_model_json2 == message_input_stateless_model_json + message_request_model_json2 = message_request_model.to_dict() + assert message_request_model_json2 == message_request_model_json -class TestModel_MessageOutput(): +class TestModel_MessageResponse(): """ - Test Class for MessageOutput + Test Class for MessageResponse """ - def test_message_output_serialization(self): + def test_message_response_serialization(self): """ - Test serialization/deserialization for MessageOutput + Test serialization/deserialization for MessageResponse """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3222,54 +6311,12 @@ def test_message_output_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_entity_model['skill'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -3288,137 +6335,122 @@ def test_message_output_serialization(self): dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - # Construct a json representation of a MessageOutput model - message_output_model_json = {} - message_output_model_json['generic'] = [runtime_response_generic_model] - message_output_model_json['intents'] = [runtime_intent_model] - message_output_model_json['entities'] = [runtime_entity_model] - message_output_model_json['actions'] = [dialog_node_action_model] - message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {} - message_output_model_json['spelling'] = message_output_spelling_model - - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model = MessageOutput.from_dict(message_output_model_json) - assert message_output_model != False - - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ - message_output_model2 = MessageOutput(**message_output_model_dict) - - # Verify the model instances are equivalent - assert message_output_model == message_output_model2 - - # Convert model instance back to dict and verify no loss of data - message_output_model_json2 = message_output_model.to_dict() - assert message_output_model_json2 == message_output_model_json - -class TestModel_MessageOutputDebug(): - """ - Test Class for MessageOutputDebug - """ - - def test_message_output_debug_serialization(self): - """ - Test serialization/deserialization for MessageOutputDebug - """ - - # Construct dict forms of any model objects needed in order to build this model. - - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' - - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' - - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['spelling'] = message_output_spelling_model - # Construct a json representation of a MessageOutputDebug model - message_output_debug_model_json = {} - message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model_json['log_messages'] = [dialog_log_message_model] - message_output_debug_model_json['branch_exited'] = True - message_output_debug_model_json['branch_exited_reason'] = 'completed' + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) - assert message_output_debug_model != False + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ - message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Verify the model instances are equivalent - assert message_output_debug_model == message_output_debug_model2 + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model - # Convert model instance back to dict and verify no loss of data - message_output_debug_model_json2 = message_output_debug_model.to_dict() - assert message_output_debug_model_json2 == message_output_debug_model_json + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} -class TestModel_MessageOutputSpelling(): - """ - Test Class for MessageOutputSpelling - """ + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model - def test_message_output_spelling_serialization(self): - """ - Test serialization/deserialization for MessageOutputSpelling - """ + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'foo': 'bar'} - # Construct a json representation of a MessageOutputSpelling model - message_output_spelling_model_json = {} - message_output_spelling_model_json['text'] = 'testString' - message_output_spelling_model_json['original_text'] = 'testString' - message_output_spelling_model_json['suggested_text'] = 'testString' + # Construct a json representation of a MessageResponse model + message_response_model_json = {} + message_response_model_json['output'] = message_output_model + message_response_model_json['context'] = message_context_model + message_response_model_json['user_id'] = 'testString' - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) - assert message_output_spelling_model != False + # Construct a model instance of MessageResponse by calling from_dict on the json representation + message_response_model = MessageResponse.from_dict(message_response_model_json) + assert message_response_model != False - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ - message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) + # Construct a model instance of MessageResponse by calling from_dict on the json representation + message_response_model_dict = MessageResponse.from_dict(message_response_model_json).__dict__ + message_response_model2 = MessageResponse(**message_response_model_dict) # Verify the model instances are equivalent - assert message_output_spelling_model == message_output_spelling_model2 + assert message_response_model == message_response_model2 # Convert model instance back to dict and verify no loss of data - message_output_spelling_model_json2 = message_output_spelling_model.to_dict() - assert message_output_spelling_model_json2 == message_output_spelling_model_json + message_response_model_json2 = message_response_model.to_dict() + assert message_response_model_json2 == message_response_model_json -class TestModel_MessageRequest(): +class TestModel_MessageResponseStateless(): """ - Test Class for MessageRequest + Test Class for MessageResponseStateless """ - def test_message_request_serialization(self): + def test_message_response_stateless_serialization(self): """ - Test serialization/deserialization for MessageRequest + Test serialization/deserialization for MessageResponseStateless """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3468,35 +6500,68 @@ def test_message_request_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'Hello' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'my_user_id' + message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' @@ -3504,60 +6569,291 @@ def test_message_request_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' + message_context_global_stateless_model = {} # MessageContextGlobalStateless + message_context_global_stateless_model['system'] = message_context_global_system_model + message_context_global_stateless_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} - # Construct a json representation of a MessageRequest model - message_request_model_json = {} - message_request_model_json['input'] = message_input_model - message_request_model_json['context'] = message_context_model - message_request_model_json['user_id'] = 'testString' + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model - # Construct a model instance of MessageRequest by calling from_dict on the json representation - message_request_model = MessageRequest.from_dict(message_request_model_json) - assert message_request_model != False + message_context_stateless_model = {} # MessageContextStateless + message_context_stateless_model['global'] = message_context_global_stateless_model + message_context_stateless_model['skills'] = message_context_skills_model + message_context_stateless_model['integrations'] = {'foo': 'bar'} - # Construct a model instance of MessageRequest by calling from_dict on the json representation - message_request_model_dict = MessageRequest.from_dict(message_request_model_json).__dict__ - message_request_model2 = MessageRequest(**message_request_model_dict) + # Construct a json representation of a MessageResponseStateless model + message_response_stateless_model_json = {} + message_response_stateless_model_json['output'] = message_output_model + message_response_stateless_model_json['context'] = message_context_stateless_model + message_response_stateless_model_json['user_id'] = 'testString' + + # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation + message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) + assert message_response_stateless_model != False + + # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation + message_response_stateless_model_dict = MessageResponseStateless.from_dict(message_response_stateless_model_json).__dict__ + message_response_stateless_model2 = MessageResponseStateless(**message_response_stateless_model_dict) # Verify the model instances are equivalent - assert message_request_model == message_request_model2 + assert message_response_stateless_model == message_response_stateless_model2 # Convert model instance back to dict and verify no loss of data - message_request_model_json2 = message_request_model.to_dict() - assert message_request_model_json2 == message_request_model_json + message_response_stateless_model_json2 = message_response_stateless_model.to_dict() + assert message_response_stateless_model_json2 == message_response_stateless_model_json -class TestModel_MessageResponse(): +class TestModel_Pagination(): """ - Test Class for MessageResponse + Test Class for Pagination + """ + + def test_pagination_serialization(self): + """ + Test serialization/deserialization for Pagination + """ + + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 38 + pagination_model_json['matched'] = 38 + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) + + # Verify the model instances are equivalent + assert pagination_model == pagination_model2 + + # Convert model instance back to dict and verify no loss of data + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json + +class TestModel_Release(): + """ + Test Class for Release + """ + + def test_release_serialization(self): + """ + Test serialization/deserialization for Release + """ + + # Construct a json representation of a Release model + release_model_json = {} + release_model_json['description'] = 'testString' + + # Construct a model instance of Release by calling from_dict on the json representation + release_model = Release.from_dict(release_model_json) + assert release_model != False + + # Construct a model instance of Release by calling from_dict on the json representation + release_model_dict = Release.from_dict(release_model_json).__dict__ + release_model2 = Release(**release_model_dict) + + # Verify the model instances are equivalent + assert release_model == release_model2 + + # Convert model instance back to dict and verify no loss of data + release_model_json2 = release_model.to_dict() + assert release_model_json2 == release_model_json + +class TestModel_ReleaseCollection(): + """ + Test Class for ReleaseCollection + """ + + def test_release_collection_serialization(self): + """ + Test serialization/deserialization for ReleaseCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + release_model = {} # Release + release_model['description'] = 'testString' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a ReleaseCollection model + release_collection_model_json = {} + release_collection_model_json['releases'] = [release_model] + release_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model = ReleaseCollection.from_dict(release_collection_model_json) + assert release_collection_model != False + + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model_dict = ReleaseCollection.from_dict(release_collection_model_json).__dict__ + release_collection_model2 = ReleaseCollection(**release_collection_model_dict) + + # Verify the model instances are equivalent + assert release_collection_model == release_collection_model2 + + # Convert model instance back to dict and verify no loss of data + release_collection_model_json2 = release_collection_model.to_dict() + assert release_collection_model_json2 == release_collection_model_json + +class TestModel_ReleaseContent(): + """ + Test Class for ReleaseContent + """ + + def test_release_content_serialization(self): + """ + Test serialization/deserialization for ReleaseContent + """ + + # Construct a json representation of a ReleaseContent model + release_content_model_json = {} + + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model = ReleaseContent.from_dict(release_content_model_json) + assert release_content_model != False + + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model_dict = ReleaseContent.from_dict(release_content_model_json).__dict__ + release_content_model2 = ReleaseContent(**release_content_model_dict) + + # Verify the model instances are equivalent + assert release_content_model == release_content_model2 + + # Convert model instance back to dict and verify no loss of data + release_content_model_json2 = release_content_model.to_dict() + assert release_content_model_json2 == release_content_model_json + +class TestModel_ReleaseSkill(): + """ + Test Class for ReleaseSkill + """ + + def test_release_skill_serialization(self): + """ + Test serialization/deserialization for ReleaseSkill + """ + + # Construct a json representation of a ReleaseSkill model + release_skill_model_json = {} + release_skill_model_json['skill_id'] = 'testString' + release_skill_model_json['type'] = 'dialog' + release_skill_model_json['snapshot'] = 'testString' + + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model = ReleaseSkill.from_dict(release_skill_model_json) + assert release_skill_model != False + + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model_dict = ReleaseSkill.from_dict(release_skill_model_json).__dict__ + release_skill_model2 = ReleaseSkill(**release_skill_model_dict) + + # Verify the model instances are equivalent + assert release_skill_model == release_skill_model2 + + # Convert model instance back to dict and verify no loss of data + release_skill_model_json2 = release_skill_model.to_dict() + assert release_skill_model_json2 == release_skill_model_json + +class TestModel_RequestAnalytics(): + """ + Test Class for RequestAnalytics + """ + + def test_request_analytics_serialization(self): + """ + Test serialization/deserialization for RequestAnalytics + """ + + # Construct a json representation of a RequestAnalytics model + request_analytics_model_json = {} + request_analytics_model_json['browser'] = 'testString' + request_analytics_model_json['device'] = 'testString' + request_analytics_model_json['pageUrl'] = 'testString' + + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model = RequestAnalytics.from_dict(request_analytics_model_json) + assert request_analytics_model != False + + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model_dict = RequestAnalytics.from_dict(request_analytics_model_json).__dict__ + request_analytics_model2 = RequestAnalytics(**request_analytics_model_dict) + + # Verify the model instances are equivalent + assert request_analytics_model == request_analytics_model2 + + # Convert model instance back to dict and verify no loss of data + request_analytics_model_json2 = request_analytics_model.to_dict() + assert request_analytics_model_json2 == request_analytics_model_json + +class TestModel_ResponseGenericChannel(): + """ + Test Class for ResponseGenericChannel + """ + + def test_response_generic_channel_serialization(self): + """ + Test serialization/deserialization for ResponseGenericChannel + """ + + # Construct a json representation of a ResponseGenericChannel model + response_generic_channel_model_json = {} + response_generic_channel_model_json['channel'] = 'testString' + + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) + assert response_generic_channel_model != False + + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ + response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) + + # Verify the model instances are equivalent + assert response_generic_channel_model == response_generic_channel_model2 + + # Convert model instance back to dict and verify no loss of data + response_generic_channel_model_json2 = response_generic_channel_model.to_dict() + assert response_generic_channel_model_json2 == response_generic_channel_model_json + +class TestModel_RuntimeEntity(): + """ + Test Class for RuntimeEntity """ - def test_message_response_serialization(self): + def test_runtime_entity_serialization(self): """ - Test serialization/deserialization for MessageResponse + Test serialization/deserialization for RuntimeEntity """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] @@ -3597,777 +6893,1001 @@ def test_message_response_serialization(self): runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + # Construct a json representation of a RuntimeEntity model + runtime_entity_model_json = {} + runtime_entity_model_json['entity'] = 'testString' + runtime_entity_model_json['location'] = [38] + runtime_entity_model_json['value'] = 'testString' + runtime_entity_model_json['confidence'] = 72.5 + runtime_entity_model_json['groups'] = [capture_group_model] + runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model_json['role'] = runtime_entity_role_model + runtime_entity_model_json['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) + assert runtime_entity_model != False - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ + runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + # Verify the model instances are equivalent + assert runtime_entity_model == runtime_entity_model2 - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model + # Convert model instance back to dict and verify no loss of data + runtime_entity_model_json2 = runtime_entity_model.to_dict() + assert runtime_entity_model_json2 == runtime_entity_model_json - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model +class TestModel_RuntimeEntityAlternative(): + """ + Test Class for RuntimeEntityAlternative + """ - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + def test_runtime_entity_alternative_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityAlternative + """ - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model_json = {} + runtime_entity_alternative_model_json['value'] = 'testString' + runtime_entity_alternative_model_json['confidence'] = 72.5 - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) + assert runtime_entity_alternative_model != False - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ + runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Verify the model instances are equivalent + assert runtime_entity_alternative_model == runtime_entity_alternative_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() + assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json + +class TestModel_RuntimeEntityInterpretation(): + """ + Test Class for RuntimeEntityInterpretation + """ + + def test_runtime_entity_interpretation_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityInterpretation + """ + + # Construct a json representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model_json = {} + runtime_entity_interpretation_model_json['calendar_type'] = 'testString' + runtime_entity_interpretation_model_json['datetime_link'] = 'testString' + runtime_entity_interpretation_model_json['festival'] = 'testString' + runtime_entity_interpretation_model_json['granularity'] = 'day' + runtime_entity_interpretation_model_json['range_link'] = 'testString' + runtime_entity_interpretation_model_json['range_modifier'] = 'testString' + runtime_entity_interpretation_model_json['relative_day'] = 72.5 + runtime_entity_interpretation_model_json['relative_month'] = 72.5 + runtime_entity_interpretation_model_json['relative_week'] = 72.5 + runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 + runtime_entity_interpretation_model_json['relative_year'] = 72.5 + runtime_entity_interpretation_model_json['specific_day'] = 72.5 + runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model_json['specific_month'] = 72.5 + runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 + runtime_entity_interpretation_model_json['specific_year'] = 72.5 + runtime_entity_interpretation_model_json['numeric_value'] = 72.5 + runtime_entity_interpretation_model_json['subtype'] = 'testString' + runtime_entity_interpretation_model_json['part_of_day'] = 'testString' + runtime_entity_interpretation_model_json['relative_hour'] = 72.5 + runtime_entity_interpretation_model_json['relative_minute'] = 72.5 + runtime_entity_interpretation_model_json['relative_second'] = 72.5 + runtime_entity_interpretation_model_json['specific_hour'] = 72.5 + runtime_entity_interpretation_model_json['specific_minute'] = 72.5 + runtime_entity_interpretation_model_json['specific_second'] = 72.5 + runtime_entity_interpretation_model_json['timezone'] = 'testString' + + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) + assert runtime_entity_interpretation_model != False + + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ + runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() + assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json + +class TestModel_RuntimeEntityRole(): + """ + Test Class for RuntimeEntityRole + """ + + def test_runtime_entity_role_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityRole + """ + + # Construct a json representation of a RuntimeEntityRole model + runtime_entity_role_model_json = {} + runtime_entity_role_model_json['type'] = 'date_from' + + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) + assert runtime_entity_role_model != False + + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ + runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_role_model == runtime_entity_role_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() + assert runtime_entity_role_model_json2 == runtime_entity_role_model_json + +class TestModel_RuntimeIntent(): + """ + Test Class for RuntimeIntent + """ + + def test_runtime_intent_serialization(self): + """ + Test serialization/deserialization for RuntimeIntent + """ + + # Construct a json representation of a RuntimeIntent model + runtime_intent_model_json = {} + runtime_intent_model_json['intent'] = 'testString' + runtime_intent_model_json['confidence'] = 72.5 + runtime_intent_model_json['skill'] = 'testString' + + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) + assert runtime_intent_model != False + + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ + runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) + + # Verify the model instances are equivalent + assert runtime_intent_model == runtime_intent_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_intent_model_json2 = runtime_intent_model.to_dict() + assert runtime_intent_model_json2 == runtime_intent_model_json + +class TestModel_SearchResult(): + """ + Test Class for SearchResult + """ + + def test_search_result_serialization(self): + """ + Test serialization/deserialization for SearchResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model['confidence'] = 72.5 + search_result_metadata_model['score'] = 72.5 + + search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model['body'] = ['testString'] + search_result_highlight_model['title'] = ['testString'] + search_result_highlight_model['url'] = ['testString'] + search_result_highlight_model['foo'] = ['testString'] + + search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model['text'] = 'testString' + search_result_answer_model['confidence'] = 0 + + # Construct a json representation of a SearchResult model + search_result_model_json = {} + search_result_model_json['id'] = 'testString' + search_result_model_json['result_metadata'] = search_result_metadata_model + search_result_model_json['body'] = 'testString' + search_result_model_json['title'] = 'testString' + search_result_model_json['url'] = 'testString' + search_result_model_json['highlight'] = search_result_highlight_model + search_result_model_json['answers'] = [search_result_answer_model] + + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model = SearchResult.from_dict(search_result_model_json) + assert search_result_model != False + + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ + search_result_model2 = SearchResult(**search_result_model_dict) - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Verify the model instances are equivalent + assert search_result_model == search_result_model2 - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + # Convert model instance back to dict and verify no loss of data + search_result_model_json2 = search_result_model.to_dict() + assert search_result_model_json2 == search_result_model_json - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' +class TestModel_SearchResultAnswer(): + """ + Test Class for SearchResultAnswer + """ - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + def test_search_result_answer_serialization(self): + """ + Test serialization/deserialization for SearchResultAnswer + """ - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} - message_output_model['spelling'] = message_output_spelling_model + # Construct a json representation of a SearchResultAnswer model + search_result_answer_model_json = {} + search_result_answer_model_json['text'] = 'testString' + search_result_answer_model_json['confidence'] = 0 - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model = SearchResultAnswer.from_dict(search_result_answer_model_json) + assert search_result_answer_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model_dict = SearchResultAnswer.from_dict(search_result_answer_model_json).__dict__ + search_result_answer_model2 = SearchResultAnswer(**search_result_answer_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert search_result_answer_model == search_result_answer_model2 - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + search_result_answer_model_json2 = search_result_answer_model.to_dict() + assert search_result_answer_model_json2 == search_result_answer_model_json - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } +class TestModel_SearchResultHighlight(): + """ + Test Class for SearchResultHighlight + """ - # Construct a json representation of a MessageResponse model - message_response_model_json = {} - message_response_model_json['output'] = message_output_model - message_response_model_json['context'] = message_context_model - message_response_model_json['user_id'] = 'testString' + def test_search_result_highlight_serialization(self): + """ + Test serialization/deserialization for SearchResultHighlight + """ - # Construct a model instance of MessageResponse by calling from_dict on the json representation - message_response_model = MessageResponse.from_dict(message_response_model_json) - assert message_response_model != False + # Construct a json representation of a SearchResultHighlight model + search_result_highlight_model_json = {} + search_result_highlight_model_json['body'] = ['testString'] + search_result_highlight_model_json['title'] = ['testString'] + search_result_highlight_model_json['url'] = ['testString'] + search_result_highlight_model_json['foo'] = ['testString'] - # Construct a model instance of MessageResponse by calling from_dict on the json representation - message_response_model_dict = MessageResponse.from_dict(message_response_model_json).__dict__ - message_response_model2 = MessageResponse(**message_response_model_dict) + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model = SearchResultHighlight.from_dict(search_result_highlight_model_json) + assert search_result_highlight_model != False + + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model_dict = SearchResultHighlight.from_dict(search_result_highlight_model_json).__dict__ + search_result_highlight_model2 = SearchResultHighlight(**search_result_highlight_model_dict) # Verify the model instances are equivalent - assert message_response_model == message_response_model2 + assert search_result_highlight_model == search_result_highlight_model2 # Convert model instance back to dict and verify no loss of data - message_response_model_json2 = message_response_model.to_dict() - assert message_response_model_json2 == message_response_model_json + search_result_highlight_model_json2 = search_result_highlight_model.to_dict() + assert search_result_highlight_model_json2 == search_result_highlight_model_json -class TestModel_MessageResponseStateless(): + # Test get_properties and set_properties methods. + search_result_highlight_model.set_properties({}) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': ['testString']} + search_result_highlight_model.set_properties(expected_dict) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_SearchResultMetadata(): """ - Test Class for MessageResponseStateless + Test Class for SearchResultMetadata """ - def test_message_response_stateless_serialization(self): + def test_search_result_metadata_serialization(self): """ - Test serialization/deserialization for MessageResponseStateless + Test serialization/deserialization for SearchResultMetadata """ - # Construct dict forms of any model objects needed in order to build this model. - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 + # Construct a json representation of a SearchResultMetadata model + search_result_metadata_model_json = {} + search_result_metadata_model_json['confidence'] = 72.5 + search_result_metadata_model_json['score'] = 72.5 - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model = SearchResultMetadata.from_dict(search_result_metadata_model_json) + assert search_result_metadata_model != False - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model_dict = SearchResultMetadata.from_dict(search_result_metadata_model_json).__dict__ + search_result_metadata_model2 = SearchResultMetadata(**search_result_metadata_model_dict) - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Verify the model instances are equivalent + assert search_result_metadata_model == search_result_metadata_model2 - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Convert model instance back to dict and verify no loss of data + search_result_metadata_model_json2 = search_result_metadata_model.to_dict() + assert search_result_metadata_model_json2 == search_result_metadata_model_json - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model +class TestModel_SearchSettings(): + """ + Test Class for SearchSettings + """ - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + def test_search_settings_serialization(self): + """ + Test serialization/deserialization for SearchSettings + """ - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + # Construct dict forms of any model objects needed in order to build this model. - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a json representation of a SearchSettings model + search_settings_model_json = {} + search_settings_model_json['discovery'] = search_settings_discovery_model + search_settings_model_json['messages'] = search_settings_messages_model + search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model = SearchSettings.from_dict(search_settings_model_json) + assert search_settings_model != False + + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model_dict = SearchSettings.from_dict(search_settings_model_json).__dict__ + search_settings_model2 = SearchSettings(**search_settings_model_dict) - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model + # Verify the model instances are equivalent + assert search_settings_model == search_settings_model2 - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model + # Convert model instance back to dict and verify no loss of data + search_settings_model_json2 = search_settings_model.to_dict() + assert search_settings_model_json2 == search_settings_model_json - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model +class TestModel_SearchSettingsDiscovery(): + """ + Test Class for SearchSettingsDiscovery + """ - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + def test_search_settings_discovery_serialization(self): + """ + Test serialization/deserialization for SearchSettingsDiscovery + """ - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct dict forms of any model objects needed in order to build this model. - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a json representation of a SearchSettingsDiscovery model + search_settings_discovery_model_json = {} + search_settings_discovery_model_json['instance_id'] = 'testString' + search_settings_discovery_model_json['project_id'] = 'testString' + search_settings_discovery_model_json['url'] = 'testString' + search_settings_discovery_model_json['max_primary_results'] = 10000 + search_settings_discovery_model_json['max_total_results'] = 10000 + search_settings_discovery_model_json['confidence_threshold'] = 0.0 + search_settings_discovery_model_json['highlight'] = True + search_settings_discovery_model_json['find_answers'] = True + search_settings_discovery_model_json['authentication'] = search_settings_discovery_authentication_model + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) + assert search_settings_discovery_model != False + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ + search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Verify the model instances are equivalent + assert search_settings_discovery_model == search_settings_discovery_model2 - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() + assert search_settings_discovery_model_json2 == search_settings_discovery_model_json - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model +class TestModel_SearchSettingsDiscoveryAuthentication(): + """ + Test Class for SearchSettingsDiscoveryAuthentication + """ - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' + def test_search_settings_discovery_authentication_serialization(self): + """ + Test serialization/deserialization for SearchSettingsDiscoveryAuthentication + """ - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + # Construct a json representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model_json = {} + search_settings_discovery_authentication_model_json['basic'] = 'testString' + search_settings_discovery_authentication_model_json['bearer'] = 'testString' - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} - message_output_model['spelling'] = message_output_spelling_model + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) + assert search_settings_discovery_authentication_model != False - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ + search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) - message_context_global_stateless_model = {} # MessageContextGlobalStateless - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + # Verify the model instances are equivalent + assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() + assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model +class TestModel_SearchSettingsMessages(): + """ + Test Class for SearchSettingsMessages + """ - message_context_stateless_model = {} # MessageContextStateless - message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = {} - message_context_stateless_model['integrations'] = { 'foo': 'bar' } + def test_search_settings_messages_serialization(self): + """ + Test serialization/deserialization for SearchSettingsMessages + """ - # Construct a json representation of a MessageResponseStateless model - message_response_stateless_model_json = {} - message_response_stateless_model_json['output'] = message_output_model - message_response_stateless_model_json['context'] = message_context_stateless_model - message_response_stateless_model_json['user_id'] = 'testString' + # Construct a json representation of a SearchSettingsMessages model + search_settings_messages_model_json = {} + search_settings_messages_model_json['success'] = 'testString' + search_settings_messages_model_json['error'] = 'testString' + search_settings_messages_model_json['no_result'] = 'testString' - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) - assert message_response_stateless_model != False + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) + assert search_settings_messages_model != False - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model_dict = MessageResponseStateless.from_dict(message_response_stateless_model_json).__dict__ - message_response_stateless_model2 = MessageResponseStateless(**message_response_stateless_model_dict) + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ + search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) # Verify the model instances are equivalent - assert message_response_stateless_model == message_response_stateless_model2 + assert search_settings_messages_model == search_settings_messages_model2 # Convert model instance back to dict and verify no loss of data - message_response_stateless_model_json2 = message_response_stateless_model.to_dict() - assert message_response_stateless_model_json2 == message_response_stateless_model_json + search_settings_messages_model_json2 = search_settings_messages_model.to_dict() + assert search_settings_messages_model_json2 == search_settings_messages_model_json -class TestModel_ResponseGenericChannel(): +class TestModel_SearchSettingsSchemaMapping(): """ - Test Class for ResponseGenericChannel + Test Class for SearchSettingsSchemaMapping """ - def test_response_generic_channel_serialization(self): + def test_search_settings_schema_mapping_serialization(self): """ - Test serialization/deserialization for ResponseGenericChannel + Test serialization/deserialization for SearchSettingsSchemaMapping """ - # Construct a json representation of a ResponseGenericChannel model - response_generic_channel_model_json = {} - response_generic_channel_model_json['channel'] = 'testString' + # Construct a json representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model_json = {} + search_settings_schema_mapping_model_json['url'] = 'testString' + search_settings_schema_mapping_model_json['body'] = 'testString' + search_settings_schema_mapping_model_json['title'] = 'testString' - # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation - response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) - assert response_generic_channel_model != False + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) + assert search_settings_schema_mapping_model != False - # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation - response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ - response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ + search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) # Verify the model instances are equivalent - assert response_generic_channel_model == response_generic_channel_model2 + assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 # Convert model instance back to dict and verify no loss of data - response_generic_channel_model_json2 = response_generic_channel_model.to_dict() - assert response_generic_channel_model_json2 == response_generic_channel_model_json + search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() + assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json -class TestModel_RuntimeEntity(): +class TestModel_SearchSkillWarning(): """ - Test Class for RuntimeEntity + Test Class for SearchSkillWarning """ - def test_runtime_entity_serialization(self): + def test_search_skill_warning_serialization(self): """ - Test serialization/deserialization for RuntimeEntity + Test serialization/deserialization for SearchSkillWarning """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a SearchSkillWarning model + search_skill_warning_model_json = {} + search_skill_warning_model_json['code'] = 'testString' + search_skill_warning_model_json['path'] = 'testString' + search_skill_warning_model_json['message'] = 'testString' - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) + assert search_skill_warning_model != False - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ + search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Verify the model instances are equivalent + assert search_skill_warning_model == search_skill_warning_model2 - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Convert model instance back to dict and verify no loss of data + search_skill_warning_model_json2 = search_skill_warning_model.to_dict() + assert search_skill_warning_model_json2 == search_skill_warning_model_json - # Construct a json representation of a RuntimeEntity model - runtime_entity_model_json = {} - runtime_entity_model_json['entity'] = 'testString' - runtime_entity_model_json['location'] = [38] - runtime_entity_model_json['value'] = 'testString' - runtime_entity_model_json['confidence'] = 72.5 - runtime_entity_model_json['groups'] = [capture_group_model] - runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model_json['role'] = runtime_entity_role_model +class TestModel_SessionResponse(): + """ + Test Class for SessionResponse + """ - # Construct a model instance of RuntimeEntity by calling from_dict on the json representation - runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) - assert runtime_entity_model != False + def test_session_response_serialization(self): + """ + Test serialization/deserialization for SessionResponse + """ - # Construct a model instance of RuntimeEntity by calling from_dict on the json representation - runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ - runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) + # Construct a json representation of a SessionResponse model + session_response_model_json = {} + session_response_model_json['session_id'] = 'testString' + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model = SessionResponse.from_dict(session_response_model_json) + assert session_response_model != False + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ + session_response_model2 = SessionResponse(**session_response_model_dict) # Verify the model instances are equivalent - assert runtime_entity_model == runtime_entity_model2 + assert session_response_model == session_response_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_model_json2 = runtime_entity_model.to_dict() - assert runtime_entity_model_json2 == runtime_entity_model_json + session_response_model_json2 = session_response_model.to_dict() + assert session_response_model_json2 == session_response_model_json -class TestModel_RuntimeEntityAlternative(): +class TestModel_Skill(): """ - Test Class for RuntimeEntityAlternative + Test Class for Skill """ - def test_runtime_entity_alternative_serialization(self): + def test_skill_serialization(self): """ - Test serialization/deserialization for RuntimeEntityAlternative + Test serialization/deserialization for Skill """ - # Construct a json representation of a RuntimeEntityAlternative model - runtime_entity_alternative_model_json = {} - runtime_entity_alternative_model_json['value'] = 'testString' - runtime_entity_alternative_model_json['confidence'] = 72.5 + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation - runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) - assert runtime_entity_alternative_model != False + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a json representation of a Skill model + skill_model_json = {} + skill_model_json['name'] = 'testString' + skill_model_json['description'] = 'testString' + skill_model_json['workspace'] = {'foo': 'bar'} + skill_model_json['dialog_settings'] = {'foo': 'bar'} + skill_model_json['search_settings'] = search_settings_model + skill_model_json['language'] = 'testString' + skill_model_json['type'] = 'action' + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model = Skill.from_dict(skill_model_json) + assert skill_model != False + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model_dict = Skill.from_dict(skill_model_json).__dict__ + skill_model2 = Skill(**skill_model_dict) - # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation - runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ - runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) + # Verify the model instances are equivalent + assert skill_model == skill_model2 + + # Convert model instance back to dict and verify no loss of data + skill_model_json2 = skill_model.to_dict() + assert skill_model_json2 == skill_model_json + +class TestModel_SkillImport(): + """ + Test Class for SkillImport + """ + + def test_skill_import_serialization(self): + """ + Test serialization/deserialization for SkillImport + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a json representation of a SkillImport model + skill_import_model_json = {} + skill_import_model_json['name'] = 'testString' + skill_import_model_json['description'] = 'testString' + skill_import_model_json['workspace'] = {'foo': 'bar'} + skill_import_model_json['dialog_settings'] = {'foo': 'bar'} + skill_import_model_json['search_settings'] = search_settings_model + skill_import_model_json['language'] = 'testString' + skill_import_model_json['type'] = 'action' + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model = SkillImport.from_dict(skill_import_model_json) + assert skill_import_model != False + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model_dict = SkillImport.from_dict(skill_import_model_json).__dict__ + skill_import_model2 = SkillImport(**skill_import_model_dict) # Verify the model instances are equivalent - assert runtime_entity_alternative_model == runtime_entity_alternative_model2 + assert skill_import_model == skill_import_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() - assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json + skill_import_model_json2 = skill_import_model.to_dict() + assert skill_import_model_json2 == skill_import_model_json -class TestModel_RuntimeEntityInterpretation(): +class TestModel_SkillsAsyncRequestStatus(): """ - Test Class for RuntimeEntityInterpretation + Test Class for SkillsAsyncRequestStatus """ - def test_runtime_entity_interpretation_serialization(self): + def test_skills_async_request_status_serialization(self): """ - Test serialization/deserialization for RuntimeEntityInterpretation + Test serialization/deserialization for SkillsAsyncRequestStatus """ - # Construct a json representation of a RuntimeEntityInterpretation model - runtime_entity_interpretation_model_json = {} - runtime_entity_interpretation_model_json['calendar_type'] = 'testString' - runtime_entity_interpretation_model_json['datetime_link'] = 'testString' - runtime_entity_interpretation_model_json['festival'] = 'testString' - runtime_entity_interpretation_model_json['granularity'] = 'day' - runtime_entity_interpretation_model_json['range_link'] = 'testString' - runtime_entity_interpretation_model_json['range_modifier'] = 'testString' - runtime_entity_interpretation_model_json['relative_day'] = 72.5 - runtime_entity_interpretation_model_json['relative_month'] = 72.5 - runtime_entity_interpretation_model_json['relative_week'] = 72.5 - runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 - runtime_entity_interpretation_model_json['relative_year'] = 72.5 - runtime_entity_interpretation_model_json['specific_day'] = 72.5 - runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model_json['specific_month'] = 72.5 - runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 - runtime_entity_interpretation_model_json['specific_year'] = 72.5 - runtime_entity_interpretation_model_json['numeric_value'] = 72.5 - runtime_entity_interpretation_model_json['subtype'] = 'testString' - runtime_entity_interpretation_model_json['part_of_day'] = 'testString' - runtime_entity_interpretation_model_json['relative_hour'] = 72.5 - runtime_entity_interpretation_model_json['relative_minute'] = 72.5 - runtime_entity_interpretation_model_json['relative_second'] = 72.5 - runtime_entity_interpretation_model_json['specific_hour'] = 72.5 - runtime_entity_interpretation_model_json['specific_minute'] = 72.5 - runtime_entity_interpretation_model_json['specific_second'] = 72.5 - runtime_entity_interpretation_model_json['timezone'] = 'testString' + # Construct a json representation of a SkillsAsyncRequestStatus model + skills_async_request_status_model_json = {} - # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation - runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) - assert runtime_entity_interpretation_model != False + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json) + assert skills_async_request_status_model != False - # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation - runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ - runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model_dict = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json).__dict__ + skills_async_request_status_model2 = SkillsAsyncRequestStatus(**skills_async_request_status_model_dict) # Verify the model instances are equivalent - assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 + assert skills_async_request_status_model == skills_async_request_status_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() - assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json + skills_async_request_status_model_json2 = skills_async_request_status_model.to_dict() + assert skills_async_request_status_model_json2 == skills_async_request_status_model_json -class TestModel_RuntimeEntityRole(): +class TestModel_SkillsExport(): """ - Test Class for RuntimeEntityRole + Test Class for SkillsExport """ - def test_runtime_entity_role_serialization(self): + def test_skills_export_serialization(self): """ - Test serialization/deserialization for RuntimeEntityRole + Test serialization/deserialization for SkillsExport """ - # Construct a json representation of a RuntimeEntityRole model - runtime_entity_role_model_json = {} - runtime_entity_role_model_json['type'] = 'date_from' - - # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation - runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) - assert runtime_entity_role_model != False + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation - runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ - runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + + skill_model = {} # Skill + skill_model['name'] = 'testString' + skill_model['description'] = 'testString' + skill_model['workspace'] = {'foo': 'bar'} + skill_model['dialog_settings'] = {'foo': 'bar'} + skill_model['search_settings'] = search_settings_model + skill_model['language'] = 'testString' + skill_model['type'] = 'action' + + assistant_state_model = {} # AssistantState + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Construct a json representation of a SkillsExport model + skills_export_model_json = {} + skills_export_model_json['assistant_skills'] = [skill_model] + skills_export_model_json['assistant_state'] = assistant_state_model + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model = SkillsExport.from_dict(skills_export_model_json) + assert skills_export_model != False + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model_dict = SkillsExport.from_dict(skills_export_model_json).__dict__ + skills_export_model2 = SkillsExport(**skills_export_model_dict) # Verify the model instances are equivalent - assert runtime_entity_role_model == runtime_entity_role_model2 + assert skills_export_model == skills_export_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() - assert runtime_entity_role_model_json2 == runtime_entity_role_model_json + skills_export_model_json2 = skills_export_model.to_dict() + assert skills_export_model_json2 == skills_export_model_json -class TestModel_RuntimeIntent(): +class TestModel_StatusError(): """ - Test Class for RuntimeIntent + Test Class for StatusError """ - def test_runtime_intent_serialization(self): + def test_status_error_serialization(self): """ - Test serialization/deserialization for RuntimeIntent + Test serialization/deserialization for StatusError """ - # Construct a json representation of a RuntimeIntent model - runtime_intent_model_json = {} - runtime_intent_model_json['intent'] = 'testString' - runtime_intent_model_json['confidence'] = 72.5 + # Construct a json representation of a StatusError model + status_error_model_json = {} + status_error_model_json['message'] = 'testString' - # Construct a model instance of RuntimeIntent by calling from_dict on the json representation - runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) - assert runtime_intent_model != False + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model = StatusError.from_dict(status_error_model_json) + assert status_error_model != False - # Construct a model instance of RuntimeIntent by calling from_dict on the json representation - runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ - runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model_dict = StatusError.from_dict(status_error_model_json).__dict__ + status_error_model2 = StatusError(**status_error_model_dict) # Verify the model instances are equivalent - assert runtime_intent_model == runtime_intent_model2 + assert status_error_model == status_error_model2 # Convert model instance back to dict and verify no loss of data - runtime_intent_model_json2 = runtime_intent_model.to_dict() - assert runtime_intent_model_json2 == runtime_intent_model_json + status_error_model_json2 = status_error_model.to_dict() + assert status_error_model_json2 == status_error_model_json -class TestModel_SearchResult(): +class TestModel_TurnEventActionSource(): """ - Test Class for SearchResult + Test Class for TurnEventActionSource """ - def test_search_result_serialization(self): + def test_turn_event_action_source_serialization(self): """ - Test serialization/deserialization for SearchResult + Test serialization/deserialization for TurnEventActionSource """ - # Construct dict forms of any model objects needed in order to build this model. - - search_result_metadata_model = {} # SearchResultMetadata - search_result_metadata_model['confidence'] = 72.5 - search_result_metadata_model['score'] = 72.5 - - search_result_highlight_model = {} # SearchResultHighlight - search_result_highlight_model['body'] = ['testString'] - search_result_highlight_model['title'] = ['testString'] - search_result_highlight_model['url'] = ['testString'] - search_result_highlight_model['foo'] = ['testString'] - - search_result_answer_model = {} # SearchResultAnswer - search_result_answer_model['text'] = 'testString' - search_result_answer_model['confidence'] = 0 - - # Construct a json representation of a SearchResult model - search_result_model_json = {} - search_result_model_json['id'] = 'testString' - search_result_model_json['result_metadata'] = search_result_metadata_model - search_result_model_json['body'] = 'testString' - search_result_model_json['title'] = 'testString' - search_result_model_json['url'] = 'testString' - search_result_model_json['highlight'] = search_result_highlight_model - search_result_model_json['answers'] = [search_result_answer_model] + # Construct a json representation of a TurnEventActionSource model + turn_event_action_source_model_json = {} + turn_event_action_source_model_json['type'] = 'action' + turn_event_action_source_model_json['action'] = 'testString' + turn_event_action_source_model_json['action_title'] = 'testString' + turn_event_action_source_model_json['condition'] = 'testString' - # Construct a model instance of SearchResult by calling from_dict on the json representation - search_result_model = SearchResult.from_dict(search_result_model_json) - assert search_result_model != False + # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation + turn_event_action_source_model = TurnEventActionSource.from_dict(turn_event_action_source_model_json) + assert turn_event_action_source_model != False - # Construct a model instance of SearchResult by calling from_dict on the json representation - search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ - search_result_model2 = SearchResult(**search_result_model_dict) + # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation + turn_event_action_source_model_dict = TurnEventActionSource.from_dict(turn_event_action_source_model_json).__dict__ + turn_event_action_source_model2 = TurnEventActionSource(**turn_event_action_source_model_dict) # Verify the model instances are equivalent - assert search_result_model == search_result_model2 + assert turn_event_action_source_model == turn_event_action_source_model2 # Convert model instance back to dict and verify no loss of data - search_result_model_json2 = search_result_model.to_dict() - assert search_result_model_json2 == search_result_model_json + turn_event_action_source_model_json2 = turn_event_action_source_model.to_dict() + assert turn_event_action_source_model_json2 == turn_event_action_source_model_json -class TestModel_SearchResultAnswer(): +class TestModel_TurnEventCalloutCallout(): """ - Test Class for SearchResultAnswer + Test Class for TurnEventCalloutCallout """ - def test_search_result_answer_serialization(self): + def test_turn_event_callout_callout_serialization(self): """ - Test serialization/deserialization for SearchResultAnswer + Test serialization/deserialization for TurnEventCalloutCallout """ - # Construct a json representation of a SearchResultAnswer model - search_result_answer_model_json = {} - search_result_answer_model_json['text'] = 'testString' - search_result_answer_model_json['confidence'] = 0 + # Construct a json representation of a TurnEventCalloutCallout model + turn_event_callout_callout_model_json = {} + turn_event_callout_callout_model_json['type'] = 'integration_interaction' + turn_event_callout_callout_model_json['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model_json['result_variable'] = 'testString' - # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation - search_result_answer_model = SearchResultAnswer.from_dict(search_result_answer_model_json) - assert search_result_answer_model != False + # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation + turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) + assert turn_event_callout_callout_model != False - # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation - search_result_answer_model_dict = SearchResultAnswer.from_dict(search_result_answer_model_json).__dict__ - search_result_answer_model2 = SearchResultAnswer(**search_result_answer_model_dict) + # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation + turn_event_callout_callout_model_dict = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json).__dict__ + turn_event_callout_callout_model2 = TurnEventCalloutCallout(**turn_event_callout_callout_model_dict) # Verify the model instances are equivalent - assert search_result_answer_model == search_result_answer_model2 + assert turn_event_callout_callout_model == turn_event_callout_callout_model2 # Convert model instance back to dict and verify no loss of data - search_result_answer_model_json2 = search_result_answer_model.to_dict() - assert search_result_answer_model_json2 == search_result_answer_model_json + turn_event_callout_callout_model_json2 = turn_event_callout_callout_model.to_dict() + assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json -class TestModel_SearchResultHighlight(): +class TestModel_TurnEventCalloutError(): """ - Test Class for SearchResultHighlight + Test Class for TurnEventCalloutError """ - def test_search_result_highlight_serialization(self): + def test_turn_event_callout_error_serialization(self): """ - Test serialization/deserialization for SearchResultHighlight + Test serialization/deserialization for TurnEventCalloutError """ - # Construct a json representation of a SearchResultHighlight model - search_result_highlight_model_json = {} - search_result_highlight_model_json['body'] = ['testString'] - search_result_highlight_model_json['title'] = ['testString'] - search_result_highlight_model_json['url'] = ['testString'] - search_result_highlight_model_json['foo'] = ['testString'] + # Construct a json representation of a TurnEventCalloutError model + turn_event_callout_error_model_json = {} + turn_event_callout_error_model_json['message'] = 'testString' - # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation - search_result_highlight_model = SearchResultHighlight.from_dict(search_result_highlight_model_json) - assert search_result_highlight_model != False + # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation + turn_event_callout_error_model = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json) + assert turn_event_callout_error_model != False - # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation - search_result_highlight_model_dict = SearchResultHighlight.from_dict(search_result_highlight_model_json).__dict__ - search_result_highlight_model2 = SearchResultHighlight(**search_result_highlight_model_dict) + # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation + turn_event_callout_error_model_dict = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json).__dict__ + turn_event_callout_error_model2 = TurnEventCalloutError(**turn_event_callout_error_model_dict) # Verify the model instances are equivalent - assert search_result_highlight_model == search_result_highlight_model2 + assert turn_event_callout_error_model == turn_event_callout_error_model2 # Convert model instance back to dict and verify no loss of data - search_result_highlight_model_json2 = search_result_highlight_model.to_dict() - assert search_result_highlight_model_json2 == search_result_highlight_model_json - - # Test get_properties and set_properties methods. - search_result_highlight_model.set_properties({}) - actual_dict = search_result_highlight_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': ['testString']} - search_result_highlight_model.set_properties(expected_dict) - actual_dict = search_result_highlight_model.get_properties() - assert actual_dict == expected_dict + turn_event_callout_error_model_json2 = turn_event_callout_error_model.to_dict() + assert turn_event_callout_error_model_json2 == turn_event_callout_error_model_json -class TestModel_SearchResultMetadata(): +class TestModel_TurnEventNodeSource(): """ - Test Class for SearchResultMetadata + Test Class for TurnEventNodeSource """ - def test_search_result_metadata_serialization(self): + def test_turn_event_node_source_serialization(self): """ - Test serialization/deserialization for SearchResultMetadata + Test serialization/deserialization for TurnEventNodeSource """ - # Construct a json representation of a SearchResultMetadata model - search_result_metadata_model_json = {} - search_result_metadata_model_json['confidence'] = 72.5 - search_result_metadata_model_json['score'] = 72.5 + # Construct a json representation of a TurnEventNodeSource model + turn_event_node_source_model_json = {} + turn_event_node_source_model_json['type'] = 'dialog_node' + turn_event_node_source_model_json['dialog_node'] = 'testString' + turn_event_node_source_model_json['title'] = 'testString' + turn_event_node_source_model_json['condition'] = 'testString' - # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation - search_result_metadata_model = SearchResultMetadata.from_dict(search_result_metadata_model_json) - assert search_result_metadata_model != False + # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation + turn_event_node_source_model = TurnEventNodeSource.from_dict(turn_event_node_source_model_json) + assert turn_event_node_source_model != False - # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation - search_result_metadata_model_dict = SearchResultMetadata.from_dict(search_result_metadata_model_json).__dict__ - search_result_metadata_model2 = SearchResultMetadata(**search_result_metadata_model_dict) + # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation + turn_event_node_source_model_dict = TurnEventNodeSource.from_dict(turn_event_node_source_model_json).__dict__ + turn_event_node_source_model2 = TurnEventNodeSource(**turn_event_node_source_model_dict) # Verify the model instances are equivalent - assert search_result_metadata_model == search_result_metadata_model2 + assert turn_event_node_source_model == turn_event_node_source_model2 # Convert model instance back to dict and verify no loss of data - search_result_metadata_model_json2 = search_result_metadata_model.to_dict() - assert search_result_metadata_model_json2 == search_result_metadata_model_json + turn_event_node_source_model_json2 = turn_event_node_source_model.to_dict() + assert turn_event_node_source_model_json2 == turn_event_node_source_model_json -class TestModel_SessionResponse(): +class TestModel_TurnEventSearchError(): """ - Test Class for SessionResponse + Test Class for TurnEventSearchError """ - def test_session_response_serialization(self): + def test_turn_event_search_error_serialization(self): """ - Test serialization/deserialization for SessionResponse + Test serialization/deserialization for TurnEventSearchError """ - # Construct a json representation of a SessionResponse model - session_response_model_json = {} - session_response_model_json['session_id'] = 'testString' + # Construct a json representation of a TurnEventSearchError model + turn_event_search_error_model_json = {} + turn_event_search_error_model_json['message'] = 'testString' - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model = SessionResponse.from_dict(session_response_model_json) - assert session_response_model != False + # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation + turn_event_search_error_model = TurnEventSearchError.from_dict(turn_event_search_error_model_json) + assert turn_event_search_error_model != False - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ - session_response_model2 = SessionResponse(**session_response_model_dict) + # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation + turn_event_search_error_model_dict = TurnEventSearchError.from_dict(turn_event_search_error_model_json).__dict__ + turn_event_search_error_model2 = TurnEventSearchError(**turn_event_search_error_model_dict) # Verify the model instances are equivalent - assert session_response_model == session_response_model2 + assert turn_event_search_error_model == turn_event_search_error_model2 # Convert model instance back to dict and verify no loss of data - session_response_model_json2 = session_response_model.to_dict() - assert session_response_model_json2 == session_response_model_json + turn_event_search_error_model_json2 = turn_event_search_error_model.to_dict() + assert turn_event_search_error_model_json2 == turn_event_search_error_model_json class TestModel_LogMessageSourceAction(): """ @@ -4492,6 +8012,340 @@ def test_log_message_source_step_serialization(self): log_message_source_step_model_json2 = log_message_source_step_model.to_dict() assert log_message_source_step_model_json2 == log_message_source_step_model_json +class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventActionFinished + """ + + def test_message_output_debug_turn_event_turn_event_action_finished_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionFinished + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionFinished model + message_output_debug_turn_event_turn_event_action_finished_model_json = {} + message_output_debug_turn_event_turn_event_action_finished_model_json['event'] = 'action_finished' + message_output_debug_turn_event_turn_event_action_finished_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_action_finished_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_action_finished_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_action_finished_model_json['reason'] = 'all_steps_done' + message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'foo': 'bar'} + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_finished_model = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json) + assert message_output_debug_turn_event_turn_event_action_finished_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_finished_model_dict = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json).__dict__ + message_output_debug_turn_event_turn_event_action_finished_model2 = MessageOutputDebugTurnEventTurnEventActionFinished(**message_output_debug_turn_event_turn_event_action_finished_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_action_finished_model == message_output_debug_turn_event_turn_event_action_finished_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_action_finished_model_json2 = message_output_debug_turn_event_turn_event_action_finished_model.to_dict() + assert message_output_debug_turn_event_turn_event_action_finished_model_json2 == message_output_debug_turn_event_turn_event_action_finished_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventActionVisited + """ + + def test_message_output_debug_turn_event_turn_event_action_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionVisited model + message_output_debug_turn_event_turn_event_action_visited_model_json = {} + message_output_debug_turn_event_turn_event_action_visited_model_json['event'] = 'action_visited' + message_output_debug_turn_event_turn_event_action_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_action_visited_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_action_visited_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_action_visited_model_json['reason'] = 'intent' + message_output_debug_turn_event_turn_event_action_visited_model_json['result_variable'] = 'testString' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_visited_model = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json) + assert message_output_debug_turn_event_turn_event_action_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_visited_model_dict = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_action_visited_model2 = MessageOutputDebugTurnEventTurnEventActionVisited(**message_output_debug_turn_event_turn_event_action_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_action_visited_model == message_output_debug_turn_event_turn_event_action_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_action_visited_model_json2 = message_output_debug_turn_event_turn_event_action_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_action_visited_model_json2 == message_output_debug_turn_event_turn_event_action_visited_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventCallout(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventCallout + """ + + def test_message_output_debug_turn_event_turn_event_callout_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventCallout + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + turn_event_callout_callout_model = {} # TurnEventCalloutCallout + turn_event_callout_callout_model['type'] = 'integration_interaction' + turn_event_callout_callout_model['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model['result_variable'] = 'testString' + + turn_event_callout_error_model = {} # TurnEventCalloutError + turn_event_callout_error_model['message'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventCallout model + message_output_debug_turn_event_turn_event_callout_model_json = {} + message_output_debug_turn_event_turn_event_callout_model_json['event'] = 'callout' + message_output_debug_turn_event_turn_event_callout_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_callout_model_json['callout'] = turn_event_callout_callout_model + message_output_debug_turn_event_turn_event_callout_model_json['error'] = turn_event_callout_error_model + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_callout_model = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json) + assert message_output_debug_turn_event_turn_event_callout_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_callout_model_dict = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json).__dict__ + message_output_debug_turn_event_turn_event_callout_model2 = MessageOutputDebugTurnEventTurnEventCallout(**message_output_debug_turn_event_turn_event_callout_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_callout_model == message_output_debug_turn_event_turn_event_callout_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_callout_model_json2 = message_output_debug_turn_event_turn_event_callout_model.to_dict() + assert message_output_debug_turn_event_turn_event_callout_model_json2 == message_output_debug_turn_event_turn_event_callout_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventHandlerVisited + """ + + def test_message_output_debug_turn_event_turn_event_handler_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventHandlerVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventHandlerVisited model + message_output_debug_turn_event_turn_event_handler_visited_model_json = {} + message_output_debug_turn_event_turn_event_handler_visited_model_json['event'] = 'handler_visited' + message_output_debug_turn_event_turn_event_handler_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_handler_visited_model_json['action_start_time'] = 'testString' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_handler_visited_model = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json) + assert message_output_debug_turn_event_turn_event_handler_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_handler_visited_model_dict = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_handler_visited_model2 = MessageOutputDebugTurnEventTurnEventHandlerVisited(**message_output_debug_turn_event_turn_event_handler_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_handler_visited_model == message_output_debug_turn_event_turn_event_handler_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_handler_visited_model_json2 = message_output_debug_turn_event_turn_event_handler_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_handler_visited_model_json2 == message_output_debug_turn_event_turn_event_handler_visited_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventNodeVisited + """ + + def test_message_output_debug_turn_event_turn_event_node_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventNodeVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_node_source_model = {} # TurnEventNodeSource + turn_event_node_source_model['type'] = 'dialog_node' + turn_event_node_source_model['dialog_node'] = 'testString' + turn_event_node_source_model['title'] = 'testString' + turn_event_node_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventNodeVisited model + message_output_debug_turn_event_turn_event_node_visited_model_json = {} + message_output_debug_turn_event_turn_event_node_visited_model_json['event'] = 'node_visited' + message_output_debug_turn_event_turn_event_node_visited_model_json['source'] = turn_event_node_source_model + message_output_debug_turn_event_turn_event_node_visited_model_json['reason'] = 'welcome' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_node_visited_model = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json) + assert message_output_debug_turn_event_turn_event_node_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_node_visited_model_dict = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_node_visited_model2 = MessageOutputDebugTurnEventTurnEventNodeVisited(**message_output_debug_turn_event_turn_event_node_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_node_visited_model == message_output_debug_turn_event_turn_event_node_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_node_visited_model_json2 = message_output_debug_turn_event_turn_event_node_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_node_visited_model_json2 == message_output_debug_turn_event_turn_event_node_visited_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventSearch(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventSearch + """ + + def test_message_output_debug_turn_event_turn_event_search_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventSearch + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + turn_event_search_error_model = {} # TurnEventSearchError + turn_event_search_error_model['message'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventSearch model + message_output_debug_turn_event_turn_event_search_model_json = {} + message_output_debug_turn_event_turn_event_search_model_json['event'] = 'search' + message_output_debug_turn_event_turn_event_search_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_search_model_json['error'] = turn_event_search_error_model + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_search_model = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json) + assert message_output_debug_turn_event_turn_event_search_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_search_model_dict = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json).__dict__ + message_output_debug_turn_event_turn_event_search_model2 = MessageOutputDebugTurnEventTurnEventSearch(**message_output_debug_turn_event_turn_event_search_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_search_model == message_output_debug_turn_event_turn_event_search_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_search_model_json2 = message_output_debug_turn_event_turn_event_search_model.to_dict() + assert message_output_debug_turn_event_turn_event_search_model_json2 == message_output_debug_turn_event_turn_event_search_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventStepAnswered + """ + + def test_message_output_debug_turn_event_turn_event_step_answered_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepAnswered + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepAnswered model + message_output_debug_turn_event_turn_event_step_answered_model_json = {} + message_output_debug_turn_event_turn_event_step_answered_model_json['event'] = 'step_answered' + message_output_debug_turn_event_turn_event_step_answered_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_step_answered_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_step_answered_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_step_answered_model_json['prompted'] = True + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_answered_model = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json) + assert message_output_debug_turn_event_turn_event_step_answered_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_answered_model_dict = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json).__dict__ + message_output_debug_turn_event_turn_event_step_answered_model2 = MessageOutputDebugTurnEventTurnEventStepAnswered(**message_output_debug_turn_event_turn_event_step_answered_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_step_answered_model == message_output_debug_turn_event_turn_event_step_answered_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_step_answered_model_json2 = message_output_debug_turn_event_turn_event_step_answered_model.to_dict() + assert message_output_debug_turn_event_turn_event_step_answered_model_json2 == message_output_debug_turn_event_turn_event_step_answered_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventStepVisited + """ + + def test_message_output_debug_turn_event_turn_event_step_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepVisited model + message_output_debug_turn_event_turn_event_step_visited_model_json = {} + message_output_debug_turn_event_turn_event_step_visited_model_json['event'] = 'step_visited' + message_output_debug_turn_event_turn_event_step_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_step_visited_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_step_visited_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_step_visited_model_json['has_question'] = True + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_visited_model = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json) + assert message_output_debug_turn_event_turn_event_step_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_visited_model_dict = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_step_visited_model2 = MessageOutputDebugTurnEventTurnEventStepVisited(**message_output_debug_turn_event_turn_event_step_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_step_visited_model == message_output_debug_turn_event_turn_event_step_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_step_visited_model_json2 = message_output_debug_turn_event_turn_event_step_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio @@ -4514,7 +8368,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -4594,7 +8448,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -4624,6 +8478,35 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeDate(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeDate + """ + + def test_runtime_response_generic_runtime_response_type_date_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeDate + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeDate model + runtime_response_generic_runtime_response_type_date_model_json = {} + runtime_response_generic_runtime_response_type_date_model_json['response_type'] = 'date' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeDate by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_date_model = RuntimeResponseGenericRuntimeResponseTypeDate.from_dict(runtime_response_generic_runtime_response_type_date_model_json) + assert runtime_response_generic_runtime_response_type_date_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeDate by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_date_model_dict = RuntimeResponseGenericRuntimeResponseTypeDate.from_dict(runtime_response_generic_runtime_response_type_date_model_json).__dict__ + runtime_response_generic_runtime_response_type_date_model2 = RuntimeResponseGenericRuntimeResponseTypeDate(**runtime_response_generic_runtime_response_type_date_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_date_model == runtime_response_generic_runtime_response_type_date_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_date_model_json2 = runtime_response_generic_runtime_response_type_date_model.to_dict() + assert runtime_response_generic_runtime_response_type_date_model_json2 == runtime_response_generic_runtime_response_type_date_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe @@ -4717,6 +8600,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -4766,11 +8650,17 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -4790,6 +8680,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -4939,6 +8830,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -4988,11 +8880,17 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -5012,6 +8910,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model dialog_suggestion_value_model = {} # DialogSuggestionValue @@ -5020,7 +8919,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {} + dialog_suggestion_model['output'] = {'foo': 'bar'} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -5101,7 +9000,7 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -5141,7 +9040,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 1b6b9efb5..945c28ba5 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2022. +# (C) Copyright IBM Corp. 2016, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ _service = DiscoveryV1( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' @@ -152,7 +152,6 @@ def test_create_environment_value_error(self): with pytest.raises(ValueError): _service.create_environment(**req_copy) - def test_create_environment_value_error_with_retries(self): # Enable retries and run test_create_environment_value_error. _service.enable_retries() @@ -260,7 +259,6 @@ def test_list_environments_value_error(self): with pytest.raises(ValueError): _service.list_environments(**req_copy) - def test_list_environments_value_error_with_retries(self): # Enable retries and run test_list_environments_value_error. _service.enable_retries() @@ -337,7 +335,6 @@ def test_get_environment_value_error(self): with pytest.raises(ValueError): _service.get_environment(**req_copy) - def test_get_environment_value_error_with_retries(self): # Enable retries and run test_get_environment_value_error. _service.enable_retries() @@ -428,7 +425,6 @@ def test_update_environment_value_error(self): with pytest.raises(ValueError): _service.update_environment(**req_copy) - def test_update_environment_value_error_with_retries(self): # Enable retries and run test_update_environment_value_error. _service.enable_retries() @@ -505,7 +501,6 @@ def test_delete_environment_value_error(self): with pytest.raises(ValueError): _service.delete_environment(**req_copy) - def test_delete_environment_value_error_with_retries(self): # Enable retries and run test_delete_environment_value_error. _service.enable_retries() @@ -590,7 +585,6 @@ def test_list_fields_value_error(self): with pytest.raises(ValueError): _service.list_fields(**req_copy) - def test_list_fields_value_error_with_retries(self): # Enable retries and run test_list_fields_value_error. _service.enable_retries() @@ -622,7 +616,7 @@ def test_create_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -740,7 +734,7 @@ def test_create_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -864,7 +858,7 @@ def test_create_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -982,7 +976,7 @@ def test_create_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1076,7 +1070,6 @@ def test_create_configuration_value_error(self): with pytest.raises(ValueError): _service.create_configuration(**req_copy) - def test_create_configuration_value_error_with_retries(self): # Enable retries and run test_create_configuration_value_error. _service.enable_retries() @@ -1098,7 +1091,7 @@ def test_list_configurations_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1140,7 +1133,7 @@ def test_list_configurations_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1176,7 +1169,7 @@ def test_list_configurations_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1195,7 +1188,6 @@ def test_list_configurations_value_error(self): with pytest.raises(ValueError): _service.list_configurations(**req_copy) - def test_list_configurations_value_error_with_retries(self): # Enable retries and run test_list_configurations_value_error. _service.enable_retries() @@ -1217,7 +1209,7 @@ def test_get_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1255,7 +1247,7 @@ def test_get_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1276,7 +1268,6 @@ def test_get_configuration_value_error(self): with pytest.raises(ValueError): _service.get_configuration(**req_copy) - def test_get_configuration_value_error_with_retries(self): # Enable retries and run test_get_configuration_value_error. _service.enable_retries() @@ -1298,7 +1289,7 @@ def test_update_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1416,7 +1407,7 @@ def test_update_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1542,7 +1533,7 @@ def test_update_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1660,7 +1651,7 @@ def test_update_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1756,7 +1747,6 @@ def test_update_configuration_value_error(self): with pytest.raises(ValueError): _service.update_configuration(**req_copy) - def test_update_configuration_value_error_with_retries(self): # Enable retries and run test_update_configuration_value_error. _service.enable_retries() @@ -1837,7 +1827,6 @@ def test_delete_configuration_value_error(self): with pytest.raises(ValueError): _service.delete_configuration(**req_copy) - def test_delete_configuration_value_error_with_retries(self): # Enable retries and run test_delete_configuration_value_error. _service.enable_retries() @@ -1943,7 +1932,6 @@ def test_create_collection_value_error(self): with pytest.raises(ValueError): _service.create_collection(**req_copy) - def test_create_collection_value_error_with_retries(self): # Enable retries and run test_create_collection_value_error. _service.enable_retries() @@ -2062,7 +2050,6 @@ def test_list_collections_value_error(self): with pytest.raises(ValueError): _service.list_collections(**req_copy) - def test_list_collections_value_error_with_retries(self): # Enable retries and run test_list_collections_value_error. _service.enable_retries() @@ -2143,7 +2130,6 @@ def test_get_collection_value_error(self): with pytest.raises(ValueError): _service.get_collection(**req_copy) - def test_get_collection_value_error_with_retries(self): # Enable retries and run test_get_collection_value_error. _service.enable_retries() @@ -2239,7 +2225,6 @@ def test_update_collection_value_error(self): with pytest.raises(ValueError): _service.update_collection(**req_copy) - def test_update_collection_value_error_with_retries(self): # Enable retries and run test_update_collection_value_error. _service.enable_retries() @@ -2320,7 +2305,6 @@ def test_delete_collection_value_error(self): with pytest.raises(ValueError): _service.delete_collection(**req_copy) - def test_delete_collection_value_error_with_retries(self): # Enable retries and run test_delete_collection_value_error. _service.enable_retries() @@ -2401,7 +2385,6 @@ def test_list_collection_fields_value_error(self): with pytest.raises(ValueError): _service.list_collection_fields(**req_copy) - def test_list_collection_fields_value_error_with_retries(self): # Enable retries and run test_list_collection_fields_value_error. _service.enable_retries() @@ -2492,7 +2475,6 @@ def test_list_expansions_value_error(self): with pytest.raises(ValueError): _service.list_expansions(**req_copy) - def test_list_expansions_value_error_with_retries(self): # Enable retries and run test_list_expansions_value_error. _service.enable_retries() @@ -2590,7 +2572,6 @@ def test_create_expansions_value_error(self): with pytest.raises(ValueError): _service.create_expansions(**req_copy) - def test_create_expansions_value_error_with_retries(self): # Enable retries and run test_create_expansions_value_error. _service.enable_retries() @@ -2665,7 +2646,6 @@ def test_delete_expansions_value_error(self): with pytest.raises(ValueError): _service.delete_expansions(**req_copy) - def test_delete_expansions_value_error_with_retries(self): # Enable retries and run test_delete_expansions_value_error. _service.enable_retries() @@ -2746,7 +2726,6 @@ def test_get_tokenization_dictionary_status_value_error(self): with pytest.raises(ValueError): _service.get_tokenization_dictionary_status(**req_copy) - def test_get_tokenization_dictionary_status_value_error_with_retries(self): # Enable retries and run test_get_tokenization_dictionary_status_value_error. _service.enable_retries() @@ -2877,7 +2856,6 @@ def test_create_tokenization_dictionary_value_error(self): with pytest.raises(ValueError): _service.create_tokenization_dictionary(**req_copy) - def test_create_tokenization_dictionary_value_error_with_retries(self): # Enable retries and run test_create_tokenization_dictionary_value_error. _service.enable_retries() @@ -2952,7 +2930,6 @@ def test_delete_tokenization_dictionary_value_error(self): with pytest.raises(ValueError): _service.delete_tokenization_dictionary(**req_copy) - def test_delete_tokenization_dictionary_value_error_with_retries(self): # Enable retries and run test_delete_tokenization_dictionary_value_error. _service.enable_retries() @@ -3033,7 +3010,6 @@ def test_get_stopword_list_status_value_error(self): with pytest.raises(ValueError): _service.get_stopword_list_status(**req_copy) - def test_get_stopword_list_status_value_error_with_retries(self): # Enable retries and run test_get_stopword_list_status_value_error. _service.enable_retries() @@ -3163,7 +3139,6 @@ def test_create_stopword_list_value_error(self): with pytest.raises(ValueError): _service.create_stopword_list(**req_copy) - def test_create_stopword_list_value_error_with_retries(self): # Enable retries and run test_create_stopword_list_value_error. _service.enable_retries() @@ -3238,7 +3213,6 @@ def test_delete_stopword_list_value_error(self): with pytest.raises(ValueError): _service.delete_stopword_list(**req_copy) - def test_delete_stopword_list_value_error_with_retries(self): # Enable retries and run test_delete_stopword_list_value_error. _service.enable_retries() @@ -3375,7 +3349,6 @@ def test_add_document_value_error(self): with pytest.raises(ValueError): _service.add_document(**req_copy) - def test_add_document_value_error_with_retries(self): # Enable retries and run test_add_document_value_error. _service.enable_retries() @@ -3460,7 +3433,6 @@ def test_get_document_status_value_error(self): with pytest.raises(ValueError): _service.get_document_status(**req_copy) - def test_get_document_status_value_error_with_retries(self): # Enable retries and run test_get_document_status_value_error. _service.enable_retries() @@ -3593,7 +3565,6 @@ def test_update_document_value_error(self): with pytest.raises(ValueError): _service.update_document(**req_copy) - def test_update_document_value_error_with_retries(self): # Enable retries and run test_update_document_value_error. _service.enable_retries() @@ -3678,7 +3649,6 @@ def test_delete_document_value_error(self): with pytest.raises(ValueError): _service.delete_document(**req_copy) - def test_delete_document_value_error_with_retries(self): # Enable retries and run test_delete_document_value_error. _service.enable_retries() @@ -3710,7 +3680,7 @@ def test_query_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3812,7 +3782,7 @@ def test_query_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3850,7 +3820,7 @@ def test_query_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3871,7 +3841,6 @@ def test_query_value_error(self): with pytest.raises(ValueError): _service.query(**req_copy) - def test_query_value_error_with_retries(self): # Enable retries and run test_query_value_error. _service.enable_retries() @@ -3893,7 +3862,7 @@ def test_query_notices_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3985,7 +3954,7 @@ def test_query_notices_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4023,7 +3992,7 @@ def test_query_notices_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4044,7 +4013,6 @@ def test_query_notices_value_error(self): with pytest.raises(ValueError): _service.query_notices(**req_copy) - def test_query_notices_value_error_with_retries(self): # Enable retries and run test_query_notices_value_error. _service.enable_retries() @@ -4066,7 +4034,7 @@ def test_federated_query_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -4166,7 +4134,7 @@ def test_federated_query_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -4264,7 +4232,7 @@ def test_federated_query_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -4304,7 +4272,6 @@ def test_federated_query_value_error(self): with pytest.raises(ValueError): _service.federated_query(**req_copy) - def test_federated_query_value_error_with_retries(self): # Enable retries and run test_federated_query_value_error. _service.enable_retries() @@ -4326,7 +4293,7 @@ def test_federated_query_notices_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4407,7 +4374,7 @@ def test_federated_query_notices_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4449,7 +4416,7 @@ def test_federated_query_notices_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4470,7 +4437,6 @@ def test_federated_query_notices_value_error(self): with pytest.raises(ValueError): _service.federated_query_notices(**req_copy) - def test_federated_query_notices_value_error_with_retries(self): # Enable retries and run test_federated_query_notices_value_error. _service.enable_retries() @@ -4609,7 +4575,6 @@ def test_get_autocompletion_value_error(self): with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) - def test_get_autocompletion_value_error_with_retries(self): # Enable retries and run test_get_autocompletion_value_error. _service.enable_retries() @@ -4700,7 +4665,6 @@ def test_list_training_data_value_error(self): with pytest.raises(ValueError): _service.list_training_data(**req_copy) - def test_list_training_data_value_error_with_retries(self): # Enable retries and run test_list_training_data_value_error. _service.enable_retries() @@ -4807,7 +4771,6 @@ def test_add_training_data_value_error(self): with pytest.raises(ValueError): _service.add_training_data(**req_copy) - def test_add_training_data_value_error_with_retries(self): # Enable retries and run test_add_training_data_value_error. _service.enable_retries() @@ -4882,7 +4845,6 @@ def test_delete_all_training_data_value_error(self): with pytest.raises(ValueError): _service.delete_all_training_data(**req_copy) - def test_delete_all_training_data_value_error_with_retries(self): # Enable retries and run test_delete_all_training_data_value_error. _service.enable_retries() @@ -4967,7 +4929,6 @@ def test_get_training_data_value_error(self): with pytest.raises(ValueError): _service.get_training_data(**req_copy) - def test_get_training_data_value_error_with_retries(self): # Enable retries and run test_get_training_data_value_error. _service.enable_retries() @@ -5046,7 +5007,6 @@ def test_delete_training_data_value_error(self): with pytest.raises(ValueError): _service.delete_training_data(**req_copy) - def test_delete_training_data_value_error_with_retries(self): # Enable retries and run test_delete_training_data_value_error. _service.enable_retries() @@ -5131,7 +5091,6 @@ def test_list_training_examples_value_error(self): with pytest.raises(ValueError): _service.list_training_examples(**req_copy) - def test_list_training_examples_value_error_with_retries(self): # Enable retries and run test_list_training_examples_value_error. _service.enable_retries() @@ -5230,7 +5189,6 @@ def test_create_training_example_value_error(self): with pytest.raises(ValueError): _service.create_training_example(**req_copy) - def test_create_training_example_value_error_with_retries(self): # Enable retries and run test_create_training_example_value_error. _service.enable_retries() @@ -5313,7 +5271,6 @@ def test_delete_training_example_value_error(self): with pytest.raises(ValueError): _service.delete_training_example(**req_copy) - def test_delete_training_example_value_error_with_retries(self): # Enable retries and run test_delete_training_example_value_error. _service.enable_retries() @@ -5412,7 +5369,6 @@ def test_update_training_example_value_error(self): with pytest.raises(ValueError): _service.update_training_example(**req_copy) - def test_update_training_example_value_error_with_retries(self): # Enable retries and run test_update_training_example_value_error. _service.enable_retries() @@ -5501,7 +5457,6 @@ def test_get_training_example_value_error(self): with pytest.raises(ValueError): _service.get_training_example(**req_copy) - def test_get_training_example_value_error_with_retries(self): # Enable retries and run test_get_training_example_value_error. _service.enable_retries() @@ -5586,7 +5541,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -5699,7 +5653,6 @@ def test_create_event_value_error(self): with pytest.raises(ValueError): _service.create_event(**req_copy) - def test_create_event_value_error_with_retries(self): # Enable retries and run test_create_event_value_error. _service.enable_retries() @@ -5819,7 +5772,6 @@ def test_query_log_value_error(self): with pytest.raises(ValueError): _service.query_log(**req_copy) - def test_query_log_value_error_with_retries(self): # Enable retries and run test_query_log_value_error. _service.enable_retries() @@ -5931,7 +5883,6 @@ def test_get_metrics_query_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query(**req_copy) - def test_get_metrics_query_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_value_error. _service.enable_retries() @@ -6043,7 +5994,6 @@ def test_get_metrics_query_event_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query_event(**req_copy) - def test_get_metrics_query_event_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_event_value_error. _service.enable_retries() @@ -6155,7 +6105,6 @@ def test_get_metrics_query_no_results_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query_no_results(**req_copy) - def test_get_metrics_query_no_results_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_no_results_value_error. _service.enable_retries() @@ -6267,7 +6216,6 @@ def test_get_metrics_event_rate_value_error(self): with pytest.raises(ValueError): _service.get_metrics_event_rate(**req_copy) - def test_get_metrics_event_rate_value_error_with_retries(self): # Enable retries and run test_get_metrics_event_rate_value_error. _service.enable_retries() @@ -6375,7 +6323,6 @@ def test_get_metrics_query_token_event_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query_token_event(**req_copy) - def test_get_metrics_query_token_event_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_token_event_value_error. _service.enable_retries() @@ -6462,7 +6409,6 @@ def test_list_credentials_value_error(self): with pytest.raises(ValueError): _service.list_credentials(**req_copy) - def test_list_credentials_value_error_with_retries(self): # Enable retries and run test_list_credentials_value_error. _service.enable_retries() @@ -6607,7 +6553,6 @@ def test_create_credentials_value_error(self): with pytest.raises(ValueError): _service.create_credentials(**req_copy) - def test_create_credentials_value_error_with_retries(self): # Enable retries and run test_create_credentials_value_error. _service.enable_retries() @@ -6688,7 +6633,6 @@ def test_get_credentials_value_error(self): with pytest.raises(ValueError): _service.get_credentials(**req_copy) - def test_get_credentials_value_error_with_retries(self): # Enable retries and run test_get_credentials_value_error. _service.enable_retries() @@ -6837,7 +6781,6 @@ def test_update_credentials_value_error(self): with pytest.raises(ValueError): _service.update_credentials(**req_copy) - def test_update_credentials_value_error_with_retries(self): # Enable retries and run test_update_credentials_value_error. _service.enable_retries() @@ -6918,7 +6861,6 @@ def test_delete_credentials_value_error(self): with pytest.raises(ValueError): _service.delete_credentials(**req_copy) - def test_delete_credentials_value_error_with_retries(self): # Enable retries and run test_delete_credentials_value_error. _service.enable_retries() @@ -7005,7 +6947,6 @@ def test_list_gateways_value_error(self): with pytest.raises(ValueError): _service.list_gateways(**req_copy) - def test_list_gateways_value_error_with_retries(self): # Enable retries and run test_list_gateways_value_error. _service.enable_retries() @@ -7123,7 +7064,6 @@ def test_create_gateway_value_error(self): with pytest.raises(ValueError): _service.create_gateway(**req_copy) - def test_create_gateway_value_error_with_retries(self): # Enable retries and run test_create_gateway_value_error. _service.enable_retries() @@ -7204,7 +7144,6 @@ def test_get_gateway_value_error(self): with pytest.raises(ValueError): _service.get_gateway(**req_copy) - def test_get_gateway_value_error_with_retries(self): # Enable retries and run test_get_gateway_value_error. _service.enable_retries() @@ -7285,7 +7224,6 @@ def test_delete_gateway_value_error(self): with pytest.raises(ValueError): _service.delete_gateway(**req_copy) - def test_delete_gateway_value_error_with_retries(self): # Enable retries and run test_delete_gateway_value_error. _service.enable_retries() @@ -7318,13 +7256,8 @@ def test_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. document_counts_model = {} # DocumentCounts - document_counts_model['available'] = 0 - document_counts_model['processing'] = 0 - document_counts_model['failed'] = 0 - document_counts_model['pending'] = 26 collection_disk_usage_model = {} # CollectionDiskUsage - collection_disk_usage_model['used_bytes'] = 260 training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 0 @@ -7357,12 +7290,8 @@ def test_collection_serialization(self): # Construct a json representation of a Collection model collection_model_json = {} - collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' collection_model_json['description'] = 'testString' - collection_model_json['created'] = '2019-01-01T12:00:00Z' - collection_model_json['updated'] = '2019-01-01T12:00:00Z' - collection_model_json['status'] = 'active' collection_model_json['configuration_id'] = 'testString' collection_model_json['language'] = 'testString' collection_model_json['document_counts'] = document_counts_model @@ -7433,7 +7362,6 @@ def test_collection_disk_usage_serialization(self): # Construct a json representation of a CollectionDiskUsage model collection_disk_usage_model_json = {} - collection_disk_usage_model_json['used_bytes'] = 38 # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation collection_disk_usage_model = CollectionDiskUsage.from_dict(collection_disk_usage_model_json) @@ -7462,8 +7390,6 @@ def test_collection_usage_serialization(self): # Construct a json representation of a CollectionUsage model collection_usage_model_json = {} - collection_usage_model_json['available'] = 38 - collection_usage_model_json['maximum_allowed'] = 38 # Construct a model instance of CollectionUsage by calling from_dict on the json representation collection_usage_model = CollectionUsage.from_dict(collection_usage_model_json) @@ -7613,7 +7539,7 @@ def test_configuration_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -7680,10 +7606,7 @@ def test_configuration_serialization(self): # Construct a json representation of a Configuration model configuration_model_json = {} - configuration_model_json['configuration_id'] = 'testString' configuration_model_json['name'] = 'testString' - configuration_model_json['created'] = '2019-01-01T12:00:00Z' - configuration_model_json['updated'] = '2019-01-01T12:00:00Z' configuration_model_json['description'] = 'testString' configuration_model_json['conversions'] = conversions_model configuration_model_json['enrichments'] = [enrichment_model] @@ -7806,7 +7729,6 @@ def test_create_event_response_serialization(self): event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' - event_data_model['query_id'] = 'testString' # Construct a json representation of a CreateEventResponse model create_event_response_model_json = {} @@ -7914,7 +7836,6 @@ def test_credentials_serialization(self): # Construct a json representation of a Credentials model credentials_model_json = {} - credentials_model_json['credential_id'] = 'testString' credentials_model_json['source_type'] = 'box' credentials_model_json['credential_details'] = credential_details_model credentials_model_json['status'] = status_details_model @@ -7972,7 +7893,6 @@ def test_credentials_list_serialization(self): status_details_model['error_message'] = 'testString' credentials_model = {} # Credentials - credentials_model['credential_id'] = '00000d8c-0000-00e8-ba89-0ed5f89f718b' credentials_model['source_type'] = 'salesforce' credentials_model['credential_details'] = credential_details_model credentials_model['status'] = status_details_model @@ -8039,13 +7959,6 @@ def test_delete_configuration_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'configuration_in_use' - notice_model['created'] = '2016-09-28T12:34:00Z' - notice_model['document_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'The configuration was deleted, but it is referenced by one or more collections.' # Construct a json representation of a DeleteConfigurationResponse model delete_configuration_response_model_json = {} @@ -8170,8 +8083,6 @@ def test_disk_usage_serialization(self): # Construct a json representation of a DiskUsage model disk_usage_model_json = {} - disk_usage_model_json['used_bytes'] = 38 - disk_usage_model_json['maximum_allowed_bytes'] = 38 # Construct a model instance of DiskUsage by calling from_dict on the json representation disk_usage_model = DiskUsage.from_dict(disk_usage_model_json) @@ -8201,13 +8112,6 @@ def test_document_accepted_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' # Construct a json representation of a DocumentAccepted model document_accepted_model_json = {} @@ -8242,10 +8146,6 @@ def test_document_counts_serialization(self): # Construct a json representation of a DocumentCounts model document_counts_model_json = {} - document_counts_model_json['available'] = 26 - document_counts_model_json['processing'] = 26 - document_counts_model_json['failed'] = 26 - document_counts_model_json['pending'] = 26 # Construct a model instance of DocumentCounts by calling from_dict on the json representation document_counts_model = DocumentCounts.from_dict(document_counts_model_json) @@ -8272,27 +8172,11 @@ def test_document_status_serialization(self): Test serialization/deserialization for DocumentStatus """ - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - notice_model['notice_id'] = 'index_342' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'indexing' - notice_model['description'] = 'something bad happened' - # Construct a json representation of a DocumentStatus model document_status_model_json = {} - document_status_model_json['document_id'] = 'testString' - document_status_model_json['configuration_id'] = 'testString' - document_status_model_json['status'] = 'available' - document_status_model_json['status_description'] = 'testString' document_status_model_json['filename'] = 'testString' document_status_model_json['file_type'] = 'pdf' document_status_model_json['sha1'] = 'testString' - document_status_model_json['notices'] = [notice_model] # Construct a model instance of DocumentStatus by calling from_dict on the json representation document_status_model = DocumentStatus.from_dict(document_status_model_json) @@ -8359,7 +8243,7 @@ def test_enrichment_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8444,7 +8328,7 @@ def test_enrichment_options_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8483,16 +8367,10 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. environment_documents_model = {} # EnvironmentDocuments - environment_documents_model['available'] = 38 - environment_documents_model['maximum_allowed'] = 1000000 disk_usage_model = {} # DiskUsage - disk_usage_model['used_bytes'] = 0 - disk_usage_model['maximum_allowed_bytes'] = 85899345920 collection_usage_model = {} # CollectionUsage - collection_usage_model['available'] = 1 - collection_usage_model['maximum_allowed'] = 4 index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model @@ -8507,13 +8385,8 @@ def test_environment_serialization(self): # Construct a json representation of a Environment model environment_model_json = {} - environment_model_json['environment_id'] = 'testString' environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' - environment_model_json['created'] = '2019-01-01T12:00:00Z' - environment_model_json['updated'] = '2019-01-01T12:00:00Z' - environment_model_json['status'] = 'active' - environment_model_json['read_only'] = True environment_model_json['size'] = 'LT' environment_model_json['requested_size'] = 'testString' environment_model_json['index_capacity'] = index_capacity_model @@ -8546,8 +8419,6 @@ def test_environment_documents_serialization(self): # Construct a json representation of a EnvironmentDocuments model environment_documents_model_json = {} - environment_documents_model_json['available'] = 38 - environment_documents_model_json['maximum_allowed'] = 38 # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation environment_documents_model = EnvironmentDocuments.from_dict(environment_documents_model_json) @@ -8582,7 +8453,6 @@ def test_event_data_serialization(self): event_data_model_json['display_rank'] = 38 event_data_model_json['collection_id'] = 'testString' event_data_model_json['document_id'] = 'testString' - event_data_model_json['query_id'] = 'testString' # Construct a model instance of EventData by calling from_dict on the json representation event_data_model = EventData.from_dict(event_data_model_json) @@ -8676,8 +8546,6 @@ def test_field_serialization(self): # Construct a json representation of a Field model field_model_json = {} - field_model_json['field'] = 'testString' - field_model_json['type'] = 'nested' # Construct a model instance of Field by calling from_dict on the json representation field_model = Field.from_dict(field_model_json) @@ -8881,16 +8749,10 @@ def test_index_capacity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. environment_documents_model = {} # EnvironmentDocuments - environment_documents_model['available'] = 38 - environment_documents_model['maximum_allowed'] = 38 disk_usage_model = {} # DiskUsage - disk_usage_model['used_bytes'] = 38 - disk_usage_model['maximum_allowed_bytes'] = 38 collection_usage_model = {} # CollectionUsage - collection_usage_model['available'] = 38 - collection_usage_model['maximum_allowed'] = 38 # Construct a json representation of a IndexCapacity model index_capacity_model_json = {} @@ -8926,8 +8788,6 @@ def test_list_collection_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. field_model = {} # Field - field_model['field'] = 'warnings' - field_model['type'] = 'nested' # Construct a json representation of a ListCollectionFieldsResponse model list_collection_fields_response_model_json = {} @@ -8961,13 +8821,8 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. document_counts_model = {} # DocumentCounts - document_counts_model['available'] = 26 - document_counts_model['processing'] = 26 - document_counts_model['failed'] = 26 - document_counts_model['pending'] = 26 collection_disk_usage_model = {} # CollectionDiskUsage - collection_disk_usage_model['used_bytes'] = 38 training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 38 @@ -8999,12 +8854,8 @@ def test_list_collections_response_serialization(self): sdu_status_model['custom_fields'] = sdu_status_custom_fields_model collection_model = {} # Collection - collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' collection_model['name'] = 'example' collection_model['description'] = 'this is a demo collection' - collection_model['created'] = '2015-08-24T18:42:25.324000Z' - collection_model['updated'] = '2015-08-24T18:42:25.324000Z' - collection_model['status'] = 'active' collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' collection_model['language'] = 'en' collection_model['document_counts'] = document_counts_model @@ -9136,7 +8987,7 @@ def test_list_configurations_response_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -9202,10 +9053,7 @@ def test_list_configurations_response_serialization(self): source_model['options'] = source_options_model configuration_model = {} # Configuration - configuration_model['configuration_id'] = 'testString' configuration_model['name'] = 'testString' - configuration_model['created'] = '2019-01-01T12:00:00Z' - configuration_model['updated'] = '2019-01-01T12:00:00Z' configuration_model['description'] = 'testString' configuration_model['conversions'] = conversions_model configuration_model['enrichments'] = [enrichment_model] @@ -9244,16 +9092,10 @@ def test_list_environments_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. environment_documents_model = {} # EnvironmentDocuments - environment_documents_model['available'] = 38 - environment_documents_model['maximum_allowed'] = 38 disk_usage_model = {} # DiskUsage - disk_usage_model['used_bytes'] = 38 - disk_usage_model['maximum_allowed_bytes'] = 38 collection_usage_model = {} # CollectionUsage - collection_usage_model['available'] = 38 - collection_usage_model['maximum_allowed'] = 38 index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model @@ -9267,13 +9109,8 @@ def test_list_environments_response_serialization(self): search_status_model['last_trained'] = '2019-01-01' environment_model = {} # Environment - environment_model['environment_id'] = 'ecbda78e-fb06-40b1-a43f-a039fac0adc6' environment_model['name'] = 'byod_environment' environment_model['description'] = 'Private Data Environment' - environment_model['created'] = '2017-07-14T12:54:40.985000Z' - environment_model['updated'] = '2017-07-14T12:54:40.985000Z' - environment_model['status'] = 'active' - environment_model['read_only'] = False environment_model['size'] = 'LT' environment_model['requested_size'] = 'testString' environment_model['index_capacity'] = index_capacity_model @@ -9850,7 +9687,7 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model_json['categories'] = {} + nlu_enrichment_features_model_json['categories'] = {'foo': 'bar'} nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model @@ -10034,13 +9871,6 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} - notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = '2019-01-01T12:00:00Z' - notice_model_json['document_id'] = 'testString' - notice_model_json['query_id'] = 'testString' - notice_model_json['severity'] = 'warning' - notice_model_json['step'] = 'testString' - notice_model_json['description'] = 'testString' # Construct a model instance of Notice by calling from_dict on the json representation notice_model = Notice.from_dict(notice_model_json) @@ -10222,17 +10052,10 @@ def test_query_notices_response_serialization(self): query_result_metadata_model['confidence'] = 72.5 notice_model = {} # Notice - notice_model['notice_id'] = 'xpath_not_found' - notice_model['created'] = '2016-09-20T17:26:17Z' - notice_model['document_id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'html-to-html' - notice_model['description'] = 'The xpath expression "boom" was not found.' query_notices_result_model = {} # QueryNoticesResult query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - query_notices_result_model['metadata'] = {} + query_notices_result_model['metadata'] = {'foo': 'bar'} query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' query_notices_result_model['result_metadata'] = query_result_metadata_model query_notices_result_model['code'] = 200 @@ -10240,7 +10063,7 @@ def test_query_notices_response_serialization(self): query_notices_result_model['file_type'] = 'html' query_notices_result_model['sha1'] = 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' query_notices_result_model['notices'] = [notice_model] - query_notices_result_model['score'] = { 'foo': 'bar' } + query_notices_result_model['score'] = '1' query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -10295,18 +10118,11 @@ def test_query_notices_result_serialization(self): query_result_metadata_model['confidence'] = 72.5 notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' # Construct a json representation of a QueryNoticesResult model query_notices_result_model_json = {} query_notices_result_model_json['id'] = 'testString' - query_notices_result_model_json['metadata'] = {} + query_notices_result_model_json['metadata'] = {'foo': 'bar'} query_notices_result_model_json['collection_id'] = 'testString' query_notices_result_model_json['result_metadata'] = query_result_metadata_model query_notices_result_model_json['code'] = 38 @@ -10314,7 +10130,7 @@ def test_query_notices_result_serialization(self): query_notices_result_model_json['file_type'] = 'pdf' query_notices_result_model_json['sha1'] = 'testString' query_notices_result_model_json['notices'] = [notice_model] - query_notices_result_model_json['foo'] = { 'foo': 'bar' } + query_notices_result_model_json['foo'] = 'testString' # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation query_notices_result_model = QueryNoticesResult.from_dict(query_notices_result_model_json) @@ -10336,7 +10152,7 @@ def test_query_notices_result_serialization(self): actual_dict = query_notices_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': 'testString'} query_notices_result_model.set_properties(expected_dict) actual_dict = query_notices_result_model.get_properties() assert actual_dict == expected_dict @@ -10393,10 +10209,10 @@ def test_query_response_serialization(self): query_result_model = {} # QueryResult query_result_model['id'] = 'watson-generated ID' - query_result_model['metadata'] = {} + query_result_model['metadata'] = {'foo': 'bar'} query_result_model['collection_id'] = 'testString' query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['score'] = { 'foo': 'bar' } + query_result_model['score'] = '1' query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -10459,10 +10275,10 @@ def test_query_result_serialization(self): # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['id'] = 'testString' - query_result_model_json['metadata'] = {} + query_result_model_json['metadata'] = {'foo': 'bar'} query_result_model_json['collection_id'] = 'testString' query_result_model_json['result_metadata'] = query_result_metadata_model - query_result_model_json['foo'] = { 'foo': 'bar' } + query_result_model_json['foo'] = 'testString' # Construct a model instance of QueryResult by calling from_dict on the json representation query_result_model = QueryResult.from_dict(query_result_model_json) @@ -10484,7 +10300,7 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': 'testString'} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict @@ -10612,7 +10428,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{}] + query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -11777,7 +11593,7 @@ def test_query_top_hits_aggregation_serialization(self): query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{}] + query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] # Construct a json representation of a QueryTopHitsAggregation model query_top_hits_aggregation_model_json = {} diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 500d6a127..08c84b145 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2021. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,41 +35,1177 @@ _service = DiscoveryV2( authenticator=NoAuthAuthenticator(), - version=version - ) + version=version, +) _base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + +############################################################################## +# Start of Service: Projects +############################################################################## +# region + +class TestListProjects(): + """ + Test Class for list_projects + """ + + @responses.activate + def test_list_projects_all_params(self): + """ + list_projects() + """ + # Set up mock + url = preprocess_url('/v2/projects') + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_projects() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_projects_all_params_with_retries(self): + # Enable retries and run test_list_projects_all_params. + _service.enable_retries() + self.test_list_projects_all_params() + + # Disable retries and run test_list_projects_all_params. + _service.disable_retries() + self.test_list_projects_all_params() + + @responses.activate + def test_list_projects_value_error(self): + """ + test_list_projects_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects') + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_projects(**req_copy) + + def test_list_projects_value_error_with_retries(self): + # Enable retries and run test_list_projects_value_error. + _service.enable_retries() + self.test_list_projects_value_error() + + # Disable retries and run test_list_projects_value_error. + _service.disable_retries() + self.test_list_projects_value_error() + +class TestCreateProject(): + """ + Test Class for create_project + """ + + @responses.activate + def test_create_project_all_params(self): + """ + create_project() + """ + # Set up mock + url = preprocess_url('/v2/projects') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a DefaultQueryParamsPassages model + default_query_params_passages_model = {} + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsTableResults model + default_query_params_table_results_model = {} + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model + default_query_params_suggested_refinements_model = {} + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + # Construct a dict representation of a DefaultQueryParams model + default_query_params_model = {} + default_query_params_model['collection_ids'] = ['testString'] + default_query_params_model['passages'] = default_query_params_passages_model + default_query_params_model['table_results'] = default_query_params_table_results_model + default_query_params_model['aggregation'] = 'testString' + default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model['spelling_suggestions'] = True + default_query_params_model['highlight'] = True + default_query_params_model['count'] = 38 + default_query_params_model['sort'] = 'testString' + default_query_params_model['return'] = ['testString'] + + # Set up parameter values + name = 'testString' + type = 'document_retrieval' + default_query_parameters = default_query_params_model + + # Invoke method + response = _service.create_project( + name, + type, + default_query_parameters=default_query_parameters, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['type'] == 'document_retrieval' + assert req_body['default_query_parameters'] == default_query_params_model + + def test_create_project_all_params_with_retries(self): + # Enable retries and run test_create_project_all_params. + _service.enable_retries() + self.test_create_project_all_params() + + # Disable retries and run test_create_project_all_params. + _service.disable_retries() + self.test_create_project_all_params() + + @responses.activate + def test_create_project_value_error(self): + """ + test_create_project_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a DefaultQueryParamsPassages model + default_query_params_passages_model = {} + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsTableResults model + default_query_params_table_results_model = {} + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model + default_query_params_suggested_refinements_model = {} + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + # Construct a dict representation of a DefaultQueryParams model + default_query_params_model = {} + default_query_params_model['collection_ids'] = ['testString'] + default_query_params_model['passages'] = default_query_params_passages_model + default_query_params_model['table_results'] = default_query_params_table_results_model + default_query_params_model['aggregation'] = 'testString' + default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model['spelling_suggestions'] = True + default_query_params_model['highlight'] = True + default_query_params_model['count'] = 38 + default_query_params_model['sort'] = 'testString' + default_query_params_model['return'] = ['testString'] + + # Set up parameter values + name = 'testString' + type = 'document_retrieval' + default_query_parameters = default_query_params_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "name": name, + "type": type, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_project(**req_copy) + + def test_create_project_value_error_with_retries(self): + # Enable retries and run test_create_project_value_error. + _service.enable_retries() + self.test_create_project_value_error() + + # Disable retries and run test_create_project_value_error. + _service.disable_retries() + self.test_create_project_value_error() + +class TestGetProject(): + """ + Test Class for get_project + """ + + @responses.activate + def test_get_project_all_params(self): + """ + get_project() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.get_project( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_project_all_params_with_retries(self): + # Enable retries and run test_get_project_all_params. + _service.enable_retries() + self.test_get_project_all_params() + + # Disable retries and run test_get_project_all_params. + _service.disable_retries() + self.test_get_project_all_params() + + @responses.activate + def test_get_project_value_error(self): + """ + test_get_project_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_project(**req_copy) + + def test_get_project_value_error_with_retries(self): + # Enable retries and run test_get_project_value_error. + _service.enable_retries() + self.test_get_project_value_error() + + # Disable retries and run test_get_project_value_error. + _service.disable_retries() + self.test_get_project_value_error() + +class TestUpdateProject(): + """ + Test Class for update_project + """ + + @responses.activate + def test_update_project_all_params(self): + """ + update_project() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + name = 'testString' + + # Invoke method + response = _service.update_project( + project_id, + name=name, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + + def test_update_project_all_params_with_retries(self): + # Enable retries and run test_update_project_all_params. + _service.enable_retries() + self.test_update_project_all_params() + + # Disable retries and run test_update_project_all_params. + _service.disable_retries() + self.test_update_project_all_params() + + @responses.activate + def test_update_project_required_params(self): + """ + test_update_project_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.update_project( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_update_project_required_params_with_retries(self): + # Enable retries and run test_update_project_required_params. + _service.enable_retries() + self.test_update_project_required_params() + + # Disable retries and run test_update_project_required_params. + _service.disable_retries() + self.test_update_project_required_params() + + @responses.activate + def test_update_project_value_error(self): + """ + test_update_project_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_project(**req_copy) + + def test_update_project_value_error_with_retries(self): + # Enable retries and run test_update_project_value_error. + _service.enable_retries() + self.test_update_project_value_error() + + # Disable retries and run test_update_project_value_error. + _service.disable_retries() + self.test_update_project_value_error() + +class TestDeleteProject(): + """ + Test Class for delete_project + """ + + @responses.activate + def test_delete_project_all_params(self): + """ + delete_project() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.delete_project( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_project_all_params_with_retries(self): + # Enable retries and run test_delete_project_all_params. + _service.enable_retries() + self.test_delete_project_all_params() + + # Disable retries and run test_delete_project_all_params. + _service.disable_retries() + self.test_delete_project_all_params() + + @responses.activate + def test_delete_project_value_error(self): + """ + test_delete_project_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_project(**req_copy) + + def test_delete_project_value_error_with_retries(self): + # Enable retries and run test_delete_project_value_error. + _service.enable_retries() + self.test_delete_project_value_error() + + # Disable retries and run test_delete_project_value_error. + _service.disable_retries() + self.test_delete_project_value_error() + +class TestListFields(): + """ + Test Class for list_fields + """ + + @responses.activate + def test_list_fields_all_params(self): + """ + list_fields() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_ids = ['testString'] + + # Invoke method + response = _service.list_fields( + project_id, + collection_ids=collection_ids, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + + def test_list_fields_all_params_with_retries(self): + # Enable retries and run test_list_fields_all_params. + _service.enable_retries() + self.test_list_fields_all_params() + + # Disable retries and run test_list_fields_all_params. + _service.disable_retries() + self.test_list_fields_all_params() + + @responses.activate + def test_list_fields_required_params(self): + """ + test_list_fields_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.list_fields( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_fields_required_params_with_retries(self): + # Enable retries and run test_list_fields_required_params. + _service.enable_retries() + self.test_list_fields_required_params() + + # Disable retries and run test_list_fields_required_params. + _service.disable_retries() + self.test_list_fields_required_params() + + @responses.activate + def test_list_fields_value_error(self): + """ + test_list_fields_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_fields(**req_copy) + + def test_list_fields_value_error_with_retries(self): + # Enable retries and run test_list_fields_value_error. + _service.enable_retries() + self.test_list_fields_value_error() + + # Disable retries and run test_list_fields_value_error. + _service.disable_retries() + self.test_list_fields_value_error() + +# endregion +############################################################################## +# End of Service: Projects +############################################################################## + +############################################################################## +# Start of Service: Collections +############################################################################## +# region + +class TestListCollections(): + """ + Test Class for list_collections + """ + + @responses.activate + def test_list_collections_all_params(self): + """ + list_collections() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.list_collections( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_collections_all_params_with_retries(self): + # Enable retries and run test_list_collections_all_params. + _service.enable_retries() + self.test_list_collections_all_params() + + # Disable retries and run test_list_collections_all_params. + _service.disable_retries() + self.test_list_collections_all_params() + + @responses.activate + def test_list_collections_value_error(self): + """ + test_list_collections_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_collections(**req_copy) + + def test_list_collections_value_error_with_retries(self): + # Enable retries and run test_list_collections_value_error. + _service.enable_retries() + self.test_list_collections_value_error() + + # Disable retries and run test_list_collections_value_error. + _service.disable_retries() + self.test_list_collections_value_error() + +class TestCreateCollection(): + """ + Test Class for create_collection + """ + + @responses.activate + def test_create_collection_all_params(self): + """ + create_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + name = 'testString' + description = 'testString' + language = 'en' + enrichments = [collection_enrichment_model] + + # Invoke method + response = _service.create_collection( + project_id, + name, + description=description, + language=language, + enrichments=enrichments, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'en' + assert req_body['enrichments'] == [collection_enrichment_model] + + def test_create_collection_all_params_with_retries(self): + # Enable retries and run test_create_collection_all_params. + _service.enable_retries() + self.test_create_collection_all_params() + + # Disable retries and run test_create_collection_all_params. + _service.disable_retries() + self.test_create_collection_all_params() + + @responses.activate + def test_create_collection_value_error(self): + """ + test_create_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + name = 'testString' + description = 'testString' + language = 'en' + enrichments = [collection_enrichment_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_collection(**req_copy) + + def test_create_collection_value_error_with_retries(self): + # Enable retries and run test_create_collection_value_error. + _service.enable_retries() + self.test_create_collection_value_error() + + # Disable retries and run test_create_collection_value_error. + _service.disable_retries() + self.test_create_collection_value_error() + +class TestGetCollection(): + """ + Test Class for get_collection + """ + + @responses.activate + def test_get_collection_all_params(self): + """ + get_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.get_collection( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_collection_all_params_with_retries(self): + # Enable retries and run test_get_collection_all_params. + _service.enable_retries() + self.test_get_collection_all_params() + + # Disable retries and run test_get_collection_all_params. + _service.disable_retries() + self.test_get_collection_all_params() + + @responses.activate + def test_get_collection_value_error(self): + """ + test_get_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_collection(**req_copy) + + def test_get_collection_value_error_with_retries(self): + # Enable retries and run test_get_collection_value_error. + _service.enable_retries() + self.test_get_collection_value_error() + + # Disable retries and run test_get_collection_value_error. + _service.disable_retries() + self.test_get_collection_value_error() + +class TestUpdateCollection(): + """ + Test Class for update_collection + """ + + @responses.activate + def test_update_collection_all_params(self): + """ + update_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + enrichments = [collection_enrichment_model] + + # Invoke method + response = _service.update_collection( + project_id, + collection_id, + name=name, + description=description, + enrichments=enrichments, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['enrichments'] == [collection_enrichment_model] + + def test_update_collection_all_params_with_retries(self): + # Enable retries and run test_update_collection_all_params. + _service.enable_retries() + self.test_update_collection_all_params() + + # Disable retries and run test_update_collection_all_params. + _service.disable_retries() + self.test_update_collection_all_params() + + @responses.activate + def test_update_collection_value_error(self): + """ + test_update_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + enrichments = [collection_enrichment_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_collection(**req_copy) + + def test_update_collection_value_error_with_retries(self): + # Enable retries and run test_update_collection_value_error. + _service.enable_retries() + self.test_update_collection_value_error() + + # Disable retries and run test_update_collection_value_error. + _service.disable_retries() + self.test_update_collection_value_error() + +class TestDeleteCollection(): + """ + Test Class for delete_collection + """ + + @responses.activate + def test_delete_collection_all_params(self): + """ + delete_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.delete_collection( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_collection_all_params_with_retries(self): + # Enable retries and run test_delete_collection_all_params. + _service.enable_retries() + self.test_delete_collection_all_params() + + # Disable retries and run test_delete_collection_all_params. + _service.disable_retries() + self.test_delete_collection_all_params() + + @responses.activate + def test_delete_collection_value_error(self): + """ + test_delete_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_collection(**req_copy) + + def test_delete_collection_value_error_with_retries(self): + # Enable retries and run test_delete_collection_value_error. + _service.enable_retries() + self.test_delete_collection_value_error() + + # Disable retries and run test_delete_collection_value_error. + _service.disable_retries() + self.test_delete_collection_value_error() + +# endregion ############################################################################## -# Start of Service: Collections +# End of Service: Collections +############################################################################## + +############################################################################## +# Start of Service: Documents ############################################################################## # region -class TestListCollections(): +class TestListDocuments(): """ - Test Class for list_collections + Test Class for list_documents """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_list_documents_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + list_documents() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + count = 38 + status = 'testString' + has_notices = True + is_parent = True + parent_document_id = 'testString' + sha256 = 'testString' + + # Invoke method + response = _service.list_documents( + project_id, + collection_id, + count=count, + status=status, + has_notices=has_notices, + is_parent=is_parent, + parent_document_id=parent_document_id, + sha256=sha256, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'count={}'.format(count) in query_string + assert 'status={}'.format(status) in query_string + assert 'has_notices={}'.format('true' if has_notices else 'false') in query_string + assert 'is_parent={}'.format('true' if is_parent else 'false') in query_string + assert 'parent_document_id={}'.format(parent_document_id) in query_string + assert 'sha256={}'.format(sha256) in query_string + + def test_list_documents_all_params_with_retries(self): + # Enable retries and run test_list_documents_all_params. + _service.enable_retries() + self.test_list_documents_all_params() + + # Disable retries and run test_list_documents_all_params. + _service.disable_retries() + self.test_list_documents_all_params() @responses.activate - def test_list_collections_all_params(self): + def test_list_documents_required_params(self): """ - list_collections() + test_list_documents_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' responses.add(responses.GET, url, body=mock_response, @@ -78,10 +1214,12 @@ def test_list_collections_all_params(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Invoke method - response = _service.list_collections( + response = _service.list_documents( project_id, + collection_id, headers={} ) @@ -89,15 +1227,23 @@ def test_list_collections_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_documents_required_params_with_retries(self): + # Enable retries and run test_list_documents_required_params. + _service.enable_retries() + self.test_list_documents_required_params() + + # Disable retries and run test_list_documents_required_params. + _service.disable_retries() + self.test_list_documents_required_params() @responses.activate - def test_list_collections_value_error(self): + def test_list_documents_value_error(self): """ - test_list_collections_value_error() + test_list_documents_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' responses.add(responses.GET, url, body=mock_response, @@ -106,143 +1252,168 @@ def test_list_collections_value_error(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "collection_id": collection_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_collections(**req_copy) + _service.list_documents(**req_copy) + + def test_list_documents_value_error_with_retries(self): + # Enable retries and run test_list_documents_value_error. + _service.enable_retries() + self.test_list_documents_value_error() + + # Disable retries and run test_list_documents_value_error. + _service.disable_retries() + self.test_list_documents_value_error() + +class TestAddDocument(): + """ + Test Class for add_document + """ + + @responses.activate + def test_add_document_all_params(self): + """ + add_document() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + x_watson_discovery_force = False + # Invoke method + response = _service.add_document( + project_id, + collection_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 -class TestCreateCollection(): - """ - Test Class for create_collection - """ + def test_add_document_all_params_with_retries(self): + # Enable retries and run test_add_document_all_params. + _service.enable_retries() + self.test_add_document_all_params() - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Disable retries and run test_add_document_all_params. + _service.disable_retries() + self.test_add_document_all_params() @responses.activate - def test_create_collection_all_params(self): + def test_add_document_required_params(self): """ - create_collection() + test_add_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] + status=202) # Set up parameter values project_id = 'testString' - name = 'testString' - description = 'testString' - language = 'en' - enrichments = [collection_enrichment_model] + collection_id = 'testString' # Invoke method - response = _service.create_collection( + response = _service.add_document( project_id, - name, - description=description, - language=language, - enrichments=enrichments, + collection_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['language'] == 'en' - assert req_body['enrichments'] == [collection_enrichment_model] + assert response.status_code == 202 + def test_add_document_required_params_with_retries(self): + # Enable retries and run test_add_document_required_params. + _service.enable_retries() + self.test_add_document_required_params() + + # Disable retries and run test_add_document_required_params. + _service.disable_retries() + self.test_add_document_required_params() @responses.activate - def test_create_collection_value_error(self): + def test_add_document_value_error(self): """ - test_create_collection_value_error() + test_add_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] + status=202) # Set up parameter values project_id = 'testString' - name = 'testString' - description = 'testString' - language = 'en' - enrichments = [collection_enrichment_model] + collection_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "name": name, + "collection_id": collection_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_collection(**req_copy) + _service.add_document(**req_copy) + def test_add_document_value_error_with_retries(self): + # Enable retries and run test_add_document_value_error. + _service.enable_retries() + self.test_add_document_value_error() + # Disable retries and run test_add_document_value_error. + _service.disable_retries() + self.test_add_document_value_error() -class TestGetCollection(): +class TestGetDocument(): """ - Test Class for get_collection + Test Class for get_document """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_get_collection_all_params(self): + def test_get_document_all_params(self): """ - get_collection() + get_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' responses.add(responses.GET, url, body=mock_response, @@ -252,11 +1423,13 @@ def test_get_collection_all_params(self): # Set up parameter values project_id = 'testString' collection_id = 'testString' + document_id = 'testString' # Invoke method - response = _service.get_collection( + response = _service.get_document( project_id, collection_id, + document_id, headers={} ) @@ -264,15 +1437,23 @@ def test_get_collection_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_document_all_params_with_retries(self): + # Enable retries and run test_get_document_all_params. + _service.enable_retries() + self.test_get_document_all_params() + + # Disable retries and run test_get_document_all_params. + _service.disable_retries() + self.test_get_document_all_params() @responses.activate - def test_get_collection_value_error(self): + def test_get_document_value_error(self): """ - test_get_collection_value_error() + test_get_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' responses.add(responses.GET, url, body=mock_response, @@ -282,192 +1463,291 @@ def test_get_collection_value_error(self): # Set up parameter values project_id = 'testString' collection_id = 'testString' + document_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, "collection_id": collection_id, + "document_id": document_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_collection(**req_copy) + _service.get_document(**req_copy) + def test_get_document_value_error_with_retries(self): + # Enable retries and run test_get_document_value_error. + _service.enable_retries() + self.test_get_document_value_error() + # Disable retries and run test_get_document_value_error. + _service.disable_retries() + self.test_get_document_value_error() -class TestUpdateCollection(): +class TestUpdateDocument(): """ - Test Class for update_collection + Test Class for update_document """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_update_document_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + update_document() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + x_watson_discovery_force = False + + # Invoke method + response = _service.update_document( + project_id, + collection_id, + document_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_update_document_all_params_with_retries(self): + # Enable retries and run test_update_document_all_params. + _service.enable_retries() + self.test_update_document_all_params() + + # Disable retries and run test_update_document_all_params. + _service.disable_retries() + self.test_update_document_all_params() @responses.activate - def test_update_collection_all_params(self): + def test_update_document_required_params(self): """ - update_collection() + test_update_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] + status=202) # Set up parameter values project_id = 'testString' collection_id = 'testString' - name = 'testString' - description = 'testString' - enrichments = [collection_enrichment_model] + document_id = 'testString' # Invoke method - response = _service.update_collection( + response = _service.update_document( project_id, collection_id, - name=name, - description=description, - enrichments=enrichments, + document_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['enrichments'] == [collection_enrichment_model] + assert response.status_code == 202 + def test_update_document_required_params_with_retries(self): + # Enable retries and run test_update_document_required_params. + _service.enable_retries() + self.test_update_document_required_params() + + # Disable retries and run test_update_document_required_params. + _service.disable_retries() + self.test_update_document_required_params() @responses.activate - def test_update_collection_value_error(self): + def test_update_document_value_error(self): """ - test_update_collection_value_error() + test_update_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] + status=202) # Set up parameter values project_id = 'testString' collection_id = 'testString' - name = 'testString' - description = 'testString' - enrichments = [collection_enrichment_model] + document_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, "collection_id": collection_id, + "document_id": document_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_collection(**req_copy) + _service.update_document(**req_copy) + def test_update_document_value_error_with_retries(self): + # Enable retries and run test_update_document_value_error. + _service.enable_retries() + self.test_update_document_value_error() + # Disable retries and run test_update_document_value_error. + _service.disable_retries() + self.test_update_document_value_error() -class TestDeleteCollection(): +class TestDeleteDocument(): """ - Test Class for delete_collection + Test Class for delete_document """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_delete_document_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + delete_document() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + x_watson_discovery_force = False + + # Invoke method + response = _service.delete_document( + project_id, + collection_id, + document_id, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_document_all_params_with_retries(self): + # Enable retries and run test_delete_document_all_params. + _service.enable_retries() + self.test_delete_document_all_params() + + # Disable retries and run test_delete_document_all_params. + _service.disable_retries() + self.test_delete_document_all_params() @responses.activate - def test_delete_collection_all_params(self): + def test_delete_document_required_params(self): """ - delete_collection() + test_delete_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' collection_id = 'testString' + document_id = 'testString' # Invoke method - response = _service.delete_collection( + response = _service.delete_document( project_id, collection_id, + document_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 204 + assert response.status_code == 200 + def test_delete_document_required_params_with_retries(self): + # Enable retries and run test_delete_document_required_params. + _service.enable_retries() + self.test_delete_document_required_params() + + # Disable retries and run test_delete_document_required_params. + _service.disable_retries() + self.test_delete_document_required_params() @responses.activate - def test_delete_collection_value_error(self): + def test_delete_document_value_error(self): """ - test_delete_collection_value_error() + test_delete_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' collection_id = 'testString' + document_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, "collection_id": collection_id, + "document_id": document_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_collection(**req_copy) + _service.delete_document(**req_copy) + def test_delete_document_value_error_with_retries(self): + # Enable retries and run test_delete_document_value_error. + _service.enable_retries() + self.test_delete_document_value_error() + # Disable retries and run test_delete_document_value_error. + _service.disable_retries() + self.test_delete_document_value_error() # endregion ############################################################################## -# End of Service: Collections +# End of Service: Documents ############################################################################## ############################################################################## @@ -480,25 +1760,14 @@ class TestQuery(): Test Class for query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_all_params(self): """ query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + url = preprocess_url('/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -526,6 +1795,12 @@ def test_query_all_params(self): query_large_passages_model['find_answers'] = False query_large_passages_model['max_answers_per_passage'] = 38 + # Construct a dict representation of a QueryLargeSimilar model + query_large_similar_model = {} + query_large_similar_model['enabled'] = False + query_large_similar_model['document_ids'] = ['testString'] + query_large_similar_model['fields'] = ['testString'] + # Set up parameter values project_id = 'testString' collection_ids = ['testString'] @@ -542,6 +1817,7 @@ def test_query_all_params(self): table_results = query_large_table_results_model suggested_refinements = query_large_suggested_refinements_model passages = query_large_passages_model + similar = query_large_similar_model # Invoke method response = _service.query( @@ -560,6 +1836,7 @@ def test_query_all_params(self): table_results=table_results, suggested_refinements=suggested_refinements, passages=passages, + similar=similar, headers={} ) @@ -582,7 +1859,16 @@ def test_query_all_params(self): assert req_body['table_results'] == query_large_table_results_model assert req_body['suggested_refinements'] == query_large_suggested_refinements_model assert req_body['passages'] == query_large_passages_model + assert req_body['similar'] == query_large_similar_model + def test_query_all_params_with_retries(self): + # Enable retries and run test_query_all_params. + _service.enable_retries() + self.test_query_all_params() + + # Disable retries and run test_query_all_params. + _service.disable_retries() + self.test_query_all_params() @responses.activate def test_query_required_params(self): @@ -590,8 +1876,8 @@ def test_query_required_params(self): test_query_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + url = preprocess_url('/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -611,6 +1897,14 @@ def test_query_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_required_params_with_retries(self): + # Enable retries and run test_query_required_params. + _service.enable_retries() + self.test_query_required_params() + + # Disable retries and run test_query_required_params. + _service.disable_retries() + self.test_query_required_params() @responses.activate def test_query_value_error(self): @@ -618,8 +1912,8 @@ def test_query_value_error(self): test_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + url = preprocess_url('/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -638,31 +1932,27 @@ def test_query_value_error(self): with pytest.raises(ValueError): _service.query(**req_copy) + def test_query_value_error_with_retries(self): + # Enable retries and run test_query_value_error. + _service.enable_retries() + self.test_query_value_error() + # Disable retries and run test_query_value_error. + _service.disable_retries() + self.test_query_value_error() class TestGetAutocompletion(): """ Test Class for get_autocompletion """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_autocompletion_all_params(self): """ get_autocompletion() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') + url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -698,6 +1988,14 @@ def test_get_autocompletion_all_params(self): assert 'field={}'.format(field) in query_string assert 'count={}'.format(count) in query_string + def test_get_autocompletion_all_params_with_retries(self): + # Enable retries and run test_get_autocompletion_all_params. + _service.enable_retries() + self.test_get_autocompletion_all_params() + + # Disable retries and run test_get_autocompletion_all_params. + _service.disable_retries() + self.test_get_autocompletion_all_params() @responses.activate def test_get_autocompletion_required_params(self): @@ -705,7 +2003,7 @@ def test_get_autocompletion_required_params(self): test_get_autocompletion_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') + url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -732,6 +2030,14 @@ def test_get_autocompletion_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string + def test_get_autocompletion_required_params_with_retries(self): + # Enable retries and run test_get_autocompletion_required_params. + _service.enable_retries() + self.test_get_autocompletion_required_params() + + # Disable retries and run test_get_autocompletion_required_params. + _service.disable_retries() + self.test_get_autocompletion_required_params() @responses.activate def test_get_autocompletion_value_error(self): @@ -739,7 +2045,7 @@ def test_get_autocompletion_value_error(self): test_get_autocompletion_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') + url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -761,23 +2067,19 @@ def test_get_autocompletion_value_error(self): with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) + def test_get_autocompletion_value_error_with_retries(self): + # Enable retries and run test_get_autocompletion_value_error. + _service.enable_retries() + self.test_get_autocompletion_value_error() + # Disable retries and run test_get_autocompletion_value_error. + _service.disable_retries() + self.test_get_autocompletion_value_error() class TestQueryCollectionNotices(): """ - Test Class for query_collection_notices - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + Test Class for query_collection_notices + """ @responses.activate def test_query_collection_notices_all_params(self): @@ -785,7 +2087,7 @@ def test_query_collection_notices_all_params(self): query_collection_notices() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -826,6 +2128,14 @@ def test_query_collection_notices_all_params(self): assert 'count={}'.format(count) in query_string assert 'offset={}'.format(offset) in query_string + def test_query_collection_notices_all_params_with_retries(self): + # Enable retries and run test_query_collection_notices_all_params. + _service.enable_retries() + self.test_query_collection_notices_all_params() + + # Disable retries and run test_query_collection_notices_all_params. + _service.disable_retries() + self.test_query_collection_notices_all_params() @responses.activate def test_query_collection_notices_required_params(self): @@ -833,7 +2143,7 @@ def test_query_collection_notices_required_params(self): test_query_collection_notices_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -856,6 +2166,14 @@ def test_query_collection_notices_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_collection_notices_required_params_with_retries(self): + # Enable retries and run test_query_collection_notices_required_params. + _service.enable_retries() + self.test_query_collection_notices_required_params() + + # Disable retries and run test_query_collection_notices_required_params. + _service.disable_retries() + self.test_query_collection_notices_required_params() @responses.activate def test_query_collection_notices_value_error(self): @@ -863,7 +2181,7 @@ def test_query_collection_notices_value_error(self): test_query_collection_notices_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -885,31 +2203,27 @@ def test_query_collection_notices_value_error(self): with pytest.raises(ValueError): _service.query_collection_notices(**req_copy) + def test_query_collection_notices_value_error_with_retries(self): + # Enable retries and run test_query_collection_notices_value_error. + _service.enable_retries() + self.test_query_collection_notices_value_error() + # Disable retries and run test_query_collection_notices_value_error. + _service.disable_retries() + self.test_query_collection_notices_value_error() class TestQueryNotices(): """ Test Class for query_notices """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_notices_all_params(self): """ query_notices() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -948,6 +2262,14 @@ def test_query_notices_all_params(self): assert 'count={}'.format(count) in query_string assert 'offset={}'.format(offset) in query_string + def test_query_notices_all_params_with_retries(self): + # Enable retries and run test_query_notices_all_params. + _service.enable_retries() + self.test_query_notices_all_params() + + # Disable retries and run test_query_notices_all_params. + _service.disable_retries() + self.test_query_notices_all_params() @responses.activate def test_query_notices_required_params(self): @@ -955,7 +2277,7 @@ def test_query_notices_required_params(self): test_query_notices_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -976,6 +2298,14 @@ def test_query_notices_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_notices_required_params_with_retries(self): + # Enable retries and run test_query_notices_required_params. + _service.enable_retries() + self.test_query_notices_required_params() + + # Disable retries and run test_query_notices_required_params. + _service.disable_retries() + self.test_query_notices_required_params() @responses.activate def test_query_notices_value_error(self): @@ -983,7 +2313,7 @@ def test_query_notices_value_error(self): test_query_notices_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -1003,32 +2333,38 @@ def test_query_notices_value_error(self): with pytest.raises(ValueError): _service.query_notices(**req_copy) + def test_query_notices_value_error_with_retries(self): + # Enable retries and run test_query_notices_value_error. + _service.enable_retries() + self.test_query_notices_value_error() + # Disable retries and run test_query_notices_value_error. + _service.disable_retries() + self.test_query_notices_value_error() -class TestListFields(): +# endregion +############################################################################## +# End of Service: Queries +############################################################################## + +############################################################################## +# Start of Service: QueryModifications +############################################################################## +# region + +class TestGetStopwordList(): """ - Test Class for list_fields + Test Class for get_stopword_list """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_fields_all_params(self): + def test_get_stopword_list_all_params(self): """ - list_fields() + get_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' responses.add(responses.GET, url, body=mock_response, @@ -1037,32 +2373,36 @@ def test_list_fields_all_params(self): # Set up parameter values project_id = 'testString' - collection_ids = ['testString'] + collection_id = 'testString' # Invoke method - response = _service.list_fields( + response = _service.get_stopword_list( project_id, - collection_ids=collection_ids, + collection_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + def test_get_stopword_list_all_params_with_retries(self): + # Enable retries and run test_get_stopword_list_all_params. + _service.enable_retries() + self.test_get_stopword_list_all_params() + + # Disable retries and run test_get_stopword_list_all_params. + _service.disable_retries() + self.test_get_stopword_list_all_params() @responses.activate - def test_list_fields_required_params(self): + def test_get_stopword_list_value_error(self): """ - test_list_fields_required_params() + test_get_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' responses.add(responses.GET, url, body=mock_response, @@ -1071,27 +2411,41 @@ def test_list_fields_required_params(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' - # Invoke method - response = _service.list_fields( - project_id, - headers={} - ) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_stopword_list(**req_copy) - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 + def test_get_stopword_list_value_error_with_retries(self): + # Enable retries and run test_get_stopword_list_value_error. + _service.enable_retries() + self.test_get_stopword_list_value_error() + # Disable retries and run test_get_stopword_list_value_error. + _service.disable_retries() + self.test_get_stopword_list_value_error() + +class TestCreateStopwordList(): + """ + Test Class for create_stopword_list + """ @responses.activate - def test_list_fields_value_error(self): + def test_create_stopword_list_all_params(self): """ - test_list_fields_value_error() + create_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', @@ -1099,53 +2453,42 @@ def test_list_fields_value_error(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' + stopwords = ['testString'] - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "project_id": project_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_fields(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Queries -############################################################################## + # Invoke method + response = _service.create_stopword_list( + project_id, + collection_id, + stopwords=stopwords, + headers={} + ) -############################################################################## -# Start of Service: ComponentSettings -############################################################################## -# region + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['stopwords'] == ['testString'] -class TestGetComponentSettings(): - """ - Test Class for get_component_settings - """ + def test_create_stopword_list_all_params_with_retries(self): + # Enable retries and run test_create_stopword_list_all_params. + _service.enable_retries() + self.test_create_stopword_list_all_params() - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Disable retries and run test_create_stopword_list_all_params. + _service.disable_retries() + self.test_create_stopword_list_all_params() @responses.activate - def test_get_component_settings_all_params(self): + def test_create_stopword_list_required_params(self): """ - get_component_settings() + test_create_stopword_list_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/component_settings') - mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', @@ -1153,10 +2496,12 @@ def test_get_component_settings_all_params(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Invoke method - response = _service.get_component_settings( + response = _service.create_stopword_list( project_id, + collection_id, headers={} ) @@ -1164,16 +2509,24 @@ def test_get_component_settings_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_create_stopword_list_required_params_with_retries(self): + # Enable retries and run test_create_stopword_list_required_params. + _service.enable_retries() + self.test_create_stopword_list_required_params() + + # Disable retries and run test_create_stopword_list_required_params. + _service.disable_retries() + self.test_create_stopword_list_required_params() @responses.activate - def test_get_component_settings_value_error(self): + def test_create_stopword_list_value_error(self): """ - test_get_component_settings_value_error() + test_create_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/component_settings') - mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', @@ -1181,104 +2534,126 @@ def test_get_component_settings_value_error(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "collection_id": collection_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_component_settings(**req_copy) - + _service.create_stopword_list(**req_copy) + def test_create_stopword_list_value_error_with_retries(self): + # Enable retries and run test_create_stopword_list_value_error. + _service.enable_retries() + self.test_create_stopword_list_value_error() -# endregion -############################################################################## -# End of Service: ComponentSettings -############################################################################## - -############################################################################## -# Start of Service: Documents -############################################################################## -# region + # Disable retries and run test_create_stopword_list_value_error. + _service.disable_retries() + self.test_create_stopword_list_value_error() -class TestAddDocument(): +class TestDeleteStopwordList(): """ - Test Class for add_document + Test Class for delete_stopword_list """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_add_document_all_params(self): + def test_delete_stopword_list_all_params(self): """ - add_document() + delete_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=202) + status=204) # Set up parameter values project_id = 'testString' collection_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - x_watson_discovery_force = False # Invoke method - response = _service.add_document( + response = _service.delete_stopword_list( project_id, collection_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - x_watson_discovery_force=x_watson_discovery_force, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 204 + def test_delete_stopword_list_all_params_with_retries(self): + # Enable retries and run test_delete_stopword_list_all_params. + _service.enable_retries() + self.test_delete_stopword_list_all_params() + + # Disable retries and run test_delete_stopword_list_all_params. + _service.disable_retries() + self.test_delete_stopword_list_all_params() @responses.activate - def test_add_document_required_params(self): + def test_delete_stopword_list_value_error(self): """ - test_add_document_required_params() + test_delete_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_stopword_list(**req_copy) + + def test_delete_stopword_list_value_error_with_retries(self): + # Enable retries and run test_delete_stopword_list_value_error. + _service.enable_retries() + self.test_delete_stopword_list_value_error() + + # Disable retries and run test_delete_stopword_list_value_error. + _service.disable_retries() + self.test_delete_stopword_list_value_error() + +class TestListExpansions(): + """ + Test Class for list_expansions + """ + + @responses.activate + def test_list_expansions_all_params(self): + """ + list_expansions() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', - status=202) + status=200) # Set up parameter values project_id = 'testString' collection_id = 'testString' # Invoke method - response = _service.add_document( + response = _service.list_expansions( project_id, collection_id, headers={} @@ -1286,22 +2661,30 @@ def test_add_document_required_params(self): # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 + + def test_list_expansions_all_params_with_retries(self): + # Enable retries and run test_list_expansions_all_params. + _service.enable_retries() + self.test_list_expansions_all_params() + # Disable retries and run test_list_expansions_all_params. + _service.disable_retries() + self.test_list_expansions_all_params() @responses.activate - def test_add_document_value_error(self): + def test_list_expansions_value_error(self): """ - test_add_document_value_error() + test_list_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', - status=202) + status=200) # Set up parameter values project_id = 'testString' @@ -1315,191 +2698,212 @@ def test_add_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.add_document(**req_copy) + _service.list_expansions(**req_copy) + def test_list_expansions_value_error_with_retries(self): + # Enable retries and run test_list_expansions_value_error. + _service.enable_retries() + self.test_list_expansions_value_error() + # Disable retries and run test_list_expansions_value_error. + _service.disable_retries() + self.test_list_expansions_value_error() -class TestUpdateDocument(): +class TestCreateExpansions(): """ - Test Class for update_document + Test Class for create_expansions """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_update_document_all_params(self): + def test_create_expansions_all_params(self): """ - update_document() + create_expansions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing"}' + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=202) - - # Set up parameter values - project_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - x_watson_discovery_force = False - - # Invoke method - response = _service.update_document( - project_id, - collection_id, - document_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - x_watson_discovery_force=x_watson_discovery_force, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - + status=200) - @responses.activate - def test_update_document_required_params(self): - """ - test_update_document_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + # Construct a dict representation of a Expansion model + expansion_model = {} + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] # Set up parameter values project_id = 'testString' collection_id = 'testString' - document_id = 'testString' + expansions = [expansion_model] # Invoke method - response = _service.update_document( + response = _service.create_expansions( project_id, collection_id, - document_id, + expansions, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['expansions'] == [expansion_model] + + def test_create_expansions_all_params_with_retries(self): + # Enable retries and run test_create_expansions_all_params. + _service.enable_retries() + self.test_create_expansions_all_params() + # Disable retries and run test_create_expansions_all_params. + _service.disable_retries() + self.test_create_expansions_all_params() @responses.activate - def test_update_document_value_error(self): + def test_create_expansions_value_error(self): """ - test_update_document_value_error() + test_create_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing"}' + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=202) + status=200) + + # Construct a dict representation of a Expansion model + expansion_model = {} + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] # Set up parameter values project_id = 'testString' collection_id = 'testString' - document_id = 'testString' + expansions = [expansion_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, "collection_id": collection_id, - "document_id": document_id, + "expansions": expansions, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_document(**req_copy) + _service.create_expansions(**req_copy) + def test_create_expansions_value_error_with_retries(self): + # Enable retries and run test_create_expansions_value_error. + _service.enable_retries() + self.test_create_expansions_value_error() + # Disable retries and run test_create_expansions_value_error. + _service.disable_retries() + self.test_create_expansions_value_error() -class TestDeleteDocument(): +class TestDeleteExpansions(): """ - Test Class for delete_document + Test Class for delete_expansions """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_delete_document_all_params(self): + def test_delete_expansions_all_params(self): """ - delete_document() + delete_expansions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200) + status=204) # Set up parameter values project_id = 'testString' collection_id = 'testString' - document_id = 'testString' - x_watson_discovery_force = False # Invoke method - response = _service.delete_document( + response = _service.delete_expansions( project_id, collection_id, - document_id, - x_watson_discovery_force=x_watson_discovery_force, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 204 + def test_delete_expansions_all_params_with_retries(self): + # Enable retries and run test_delete_expansions_all_params. + _service.enable_retries() + self.test_delete_expansions_all_params() + + # Disable retries and run test_delete_expansions_all_params. + _service.disable_retries() + self.test_delete_expansions_all_params() @responses.activate - def test_delete_document_required_params(self): + def test_delete_expansions_value_error(self): """ - test_delete_document_required_params() + test_delete_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_expansions(**req_copy) + + def test_delete_expansions_value_error_with_retries(self): + # Enable retries and run test_delete_expansions_value_error. + _service.enable_retries() + self.test_delete_expansions_value_error() + + # Disable retries and run test_delete_expansions_value_error. + _service.disable_retries() + self.test_delete_expansions_value_error() + +# endregion +############################################################################## +# End of Service: QueryModifications +############################################################################## + +############################################################################## +# Start of Service: ComponentSettings +############################################################################## +# region + +class TestGetComponentSettings(): + """ + Test Class for get_component_settings + """ + + @responses.activate + def test_get_component_settings_all_params(self): + """ + get_component_settings() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/component_settings') + mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', @@ -1507,14 +2911,10 @@ def test_delete_document_required_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' - document_id = 'testString' # Invoke method - response = _service.delete_document( + response = _service.get_component_settings( project_id, - collection_id, - document_id, headers={} ) @@ -1522,16 +2922,24 @@ def test_delete_document_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_component_settings_all_params_with_retries(self): + # Enable retries and run test_get_component_settings_all_params. + _service.enable_retries() + self.test_get_component_settings_all_params() + + # Disable retries and run test_get_component_settings_all_params. + _service.disable_retries() + self.test_get_component_settings_all_params() @responses.activate - def test_delete_document_value_error(self): + def test_get_component_settings_value_error(self): """ - test_delete_document_value_error() + test_get_component_settings_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/component_settings') + mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', @@ -1539,25 +2947,28 @@ def test_delete_document_value_error(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' - document_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "collection_id": collection_id, - "document_id": document_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_document(**req_copy) + _service.get_component_settings(**req_copy) + def test_get_component_settings_value_error_with_retries(self): + # Enable retries and run test_get_component_settings_value_error. + _service.enable_retries() + self.test_get_component_settings_value_error() + # Disable retries and run test_get_component_settings_value_error. + _service.disable_retries() + self.test_get_component_settings_value_error() # endregion ############################################################################## -# End of Service: Documents +# End of Service: ComponentSettings ############################################################################## ############################################################################## @@ -1570,24 +2981,13 @@ class TestListTrainingQueries(): Test Class for list_training_queries """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_training_queries_all_params(self): """ list_training_queries() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, @@ -1608,6 +3008,14 @@ def test_list_training_queries_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_training_queries_all_params_with_retries(self): + # Enable retries and run test_list_training_queries_all_params. + _service.enable_retries() + self.test_list_training_queries_all_params() + + # Disable retries and run test_list_training_queries_all_params. + _service.disable_retries() + self.test_list_training_queries_all_params() @responses.activate def test_list_training_queries_value_error(self): @@ -1615,7 +3023,7 @@ def test_list_training_queries_value_error(self): test_list_training_queries_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, @@ -1635,31 +3043,27 @@ def test_list_training_queries_value_error(self): with pytest.raises(ValueError): _service.list_training_queries(**req_copy) + def test_list_training_queries_value_error_with_retries(self): + # Enable retries and run test_list_training_queries_value_error. + _service.enable_retries() + self.test_list_training_queries_value_error() + # Disable retries and run test_list_training_queries_value_error. + _service.disable_retries() + self.test_list_training_queries_value_error() class TestDeleteTrainingQueries(): """ Test Class for delete_training_queries """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_training_queries_all_params(self): """ delete_training_queries() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries') responses.add(responses.DELETE, url, status=204) @@ -1677,6 +3081,14 @@ def test_delete_training_queries_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_training_queries_all_params_with_retries(self): + # Enable retries and run test_delete_training_queries_all_params. + _service.enable_retries() + self.test_delete_training_queries_all_params() + + # Disable retries and run test_delete_training_queries_all_params. + _service.disable_retries() + self.test_delete_training_queries_all_params() @responses.activate def test_delete_training_queries_value_error(self): @@ -1684,7 +3096,7 @@ def test_delete_training_queries_value_error(self): test_delete_training_queries_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries') responses.add(responses.DELETE, url, status=204) @@ -1701,31 +3113,211 @@ def test_delete_training_queries_value_error(self): with pytest.raises(ValueError): _service.delete_training_queries(**req_copy) + def test_delete_training_queries_value_error_with_retries(self): + # Enable retries and run test_delete_training_queries_value_error. + _service.enable_retries() + self.test_delete_training_queries_value_error() + # Disable retries and run test_delete_training_queries_value_error. + _service.disable_retries() + self.test_delete_training_queries_value_error() class TestCreateTrainingQuery(): """ Test Class for create_training_query """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_create_training_query_all_params(self): + """ + create_training_query() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + project_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' + + # Invoke method + response = _service.create_training_query( + project_id, + natural_language_query, + examples, + filter=filter, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['natural_language_query'] == 'testString' + assert req_body['examples'] == [training_example_model] + assert req_body['filter'] == 'testString' + + def test_create_training_query_all_params_with_retries(self): + # Enable retries and run test_create_training_query_all_params. + _service.enable_retries() + self.test_create_training_query_all_params() + + # Disable retries and run test_create_training_query_all_params. + _service.disable_retries() + self.test_create_training_query_all_params() + + @responses.activate + def test_create_training_query_value_error(self): + """ + test_create_training_query_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + project_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "natural_language_query": natural_language_query, + "examples": examples, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_training_query(**req_copy) + + def test_create_training_query_value_error_with_retries(self): + # Enable retries and run test_create_training_query_value_error. + _service.enable_retries() + self.test_create_training_query_value_error() + + # Disable retries and run test_create_training_query_value_error. + _service.disable_retries() + self.test_create_training_query_value_error() + +class TestGetTrainingQuery(): + """ + Test Class for get_training_query + """ + + @responses.activate + def test_get_training_query_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + get_training_query() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Invoke method + response = _service.get_training_query( + project_id, + query_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_training_query_all_params_with_retries(self): + # Enable retries and run test_get_training_query_all_params. + _service.enable_retries() + self.test_get_training_query_all_params() + + # Disable retries and run test_get_training_query_all_params. + _service.disable_retries() + self.test_get_training_query_all_params() @responses.activate - def test_create_training_query_all_params(self): + def test_get_training_query_value_error(self): + """ + test_get_training_query_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_training_query(**req_copy) + + def test_get_training_query_value_error_with_retries(self): + # Enable retries and run test_get_training_query_value_error. + _service.enable_retries() + self.test_get_training_query_value_error() + + # Disable retries and run test_get_training_query_value_error. + _service.disable_retries() + self.test_get_training_query_value_error() + +class TestUpdateTrainingQuery(): + """ + Test Class for update_training_query + """ + + @responses.activate + def test_update_training_query_all_params(self): """ - create_training_query() + update_training_query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1741,13 +3333,15 @@ def test_create_training_query_all_params(self): # Set up parameter values project_id = 'testString' + query_id = 'testString' natural_language_query = 'testString' examples = [training_example_model] filter = 'testString' # Invoke method - response = _service.create_training_query( + response = _service.update_training_query( project_id, + query_id, natural_language_query, examples, filter=filter, @@ -1763,14 +3357,22 @@ def test_create_training_query_all_params(self): assert req_body['examples'] == [training_example_model] assert req_body['filter'] == 'testString' + def test_update_training_query_all_params_with_retries(self): + # Enable retries and run test_update_training_query_all_params. + _service.enable_retries() + self.test_update_training_query_all_params() + + # Disable retries and run test_update_training_query_all_params. + _service.disable_retries() + self.test_update_training_query_all_params() @responses.activate - def test_create_training_query_value_error(self): + def test_update_training_query_value_error(self): """ - test_create_training_query_value_error() + test_update_training_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1786,6 +3388,7 @@ def test_create_training_query_value_error(self): # Set up parameter values project_id = 'testString' + query_id = 'testString' natural_language_query = 'testString' examples = [training_example_model] filter = 'testString' @@ -1793,40 +3396,121 @@ def test_create_training_query_value_error(self): # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "query_id": query_id, "natural_language_query": natural_language_query, "examples": examples, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_training_query(**req_copy) + _service.update_training_query(**req_copy) + def test_update_training_query_value_error_with_retries(self): + # Enable retries and run test_update_training_query_value_error. + _service.enable_retries() + self.test_update_training_query_value_error() + # Disable retries and run test_update_training_query_value_error. + _service.disable_retries() + self.test_update_training_query_value_error() -class TestGetTrainingQuery(): +class TestDeleteTrainingQuery(): """ - Test Class for get_training_query + Test Class for delete_training_query """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_delete_training_query_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + delete_training_query() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Invoke method + response = _service.delete_training_query( + project_id, + query_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_training_query_all_params_with_retries(self): + # Enable retries and run test_delete_training_query_all_params. + _service.enable_retries() + self.test_delete_training_query_all_params() + + # Disable retries and run test_delete_training_query_all_params. + _service.disable_retries() + self.test_delete_training_query_all_params() @responses.activate - def test_get_training_query_all_params(self): + def test_delete_training_query_value_error(self): """ - get_training_query() + test_delete_training_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_training_query(**req_copy) + + def test_delete_training_query_value_error_with_retries(self): + # Enable retries and run test_delete_training_query_value_error. + _service.enable_retries() + self.test_delete_training_query_value_error() + + # Disable retries and run test_delete_training_query_value_error. + _service.disable_retries() + self.test_delete_training_query_value_error() + +# endregion +############################################################################## +# End of Service: TrainingData +############################################################################## + +############################################################################## +# Start of Service: Enrichments +############################################################################## +# region + +class TestListEnrichments(): + """ + Test Class for list_enrichments + """ + + @responses.activate + def test_list_enrichments_all_params(self): + """ + list_enrichments() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1835,12 +3519,10 @@ def test_get_training_query_all_params(self): # Set up parameter values project_id = 'testString' - query_id = 'testString' # Invoke method - response = _service.get_training_query( + response = _service.list_enrichments( project_id, - query_id, headers={} ) @@ -1848,15 +3530,23 @@ def test_get_training_query_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_enrichments_all_params_with_retries(self): + # Enable retries and run test_list_enrichments_all_params. + _service.enable_retries() + self.test_list_enrichments_all_params() + + # Disable retries and run test_list_enrichments_all_params. + _service.disable_retries() + self.test_list_enrichments_all_params() @responses.activate - def test_get_training_query_value_error(self): + def test_list_enrichments_value_error(self): """ - test_get_training_query_value_error() + test_list_enrichments_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1865,228 +3555,292 @@ def test_get_training_query_value_error(self): # Set up parameter values project_id = 'testString' - query_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "query_id": query_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_training_query(**req_copy) + _service.list_enrichments(**req_copy) + def test_list_enrichments_value_error_with_retries(self): + # Enable retries and run test_list_enrichments_value_error. + _service.enable_retries() + self.test_list_enrichments_value_error() + # Disable retries and run test_list_enrichments_value_error. + _service.disable_retries() + self.test_list_enrichments_value_error() -class TestUpdateTrainingQuery(): +class TestCreateEnrichment(): """ - Test Class for update_training_query + Test Class for create_enrichment """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_create_enrichment_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + create_enrichment() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'classifier' + create_enrichment_model['options'] = enrichment_options_model + + # Set up parameter values + project_id = 'testString' + enrichment = create_enrichment_model + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.create_enrichment( + project_id, + enrichment, + file=file, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + def test_create_enrichment_all_params_with_retries(self): + # Enable retries and run test_create_enrichment_all_params. + _service.enable_retries() + self.test_create_enrichment_all_params() + + # Disable retries and run test_create_enrichment_all_params. + _service.disable_retries() + self.test_create_enrichment_all_params() @responses.activate - def test_update_training_query_all_params(self): + def test_create_enrichment_required_params(self): """ - update_training_query() + test_create_enrichment_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['collection_id'] = 'testString' - training_example_model['relevance'] = 38 + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'classifier' + create_enrichment_model['options'] = enrichment_options_model # Set up parameter values project_id = 'testString' - query_id = 'testString' - natural_language_query = 'testString' - examples = [training_example_model] - filter = 'testString' + enrichment = create_enrichment_model # Invoke method - response = _service.update_training_query( + response = _service.create_enrichment( project_id, - query_id, - natural_language_query, - examples, - filter=filter, + enrichment, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['natural_language_query'] == 'testString' - assert req_body['examples'] == [training_example_model] - assert req_body['filter'] == 'testString' + def test_create_enrichment_required_params_with_retries(self): + # Enable retries and run test_create_enrichment_required_params. + _service.enable_retries() + self.test_create_enrichment_required_params() + + # Disable retries and run test_create_enrichment_required_params. + _service.disable_retries() + self.test_create_enrichment_required_params() @responses.activate - def test_update_training_query_value_error(self): + def test_create_enrichment_value_error(self): """ - test_update_training_query_value_error() + test_create_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['collection_id'] = 'testString' - training_example_model['relevance'] = 38 + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'classifier' + create_enrichment_model['options'] = enrichment_options_model # Set up parameter values project_id = 'testString' - query_id = 'testString' - natural_language_query = 'testString' - examples = [training_example_model] - filter = 'testString' + enrichment = create_enrichment_model # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "query_id": query_id, - "natural_language_query": natural_language_query, - "examples": examples, + "enrichment": enrichment, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_training_query(**req_copy) + _service.create_enrichment(**req_copy) + def test_create_enrichment_value_error_with_retries(self): + # Enable retries and run test_create_enrichment_value_error. + _service.enable_retries() + self.test_create_enrichment_value_error() + # Disable retries and run test_create_enrichment_value_error. + _service.disable_retries() + self.test_create_enrichment_value_error() -class TestDeleteTrainingQuery(): +class TestGetEnrichment(): """ - Test Class for delete_training_query + Test Class for get_enrichment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_delete_training_query_all_params(self): + def test_get_enrichment_all_params(self): """ - delete_training_query() + get_enrichment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' + responses.add(responses.GET, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' - query_id = 'testString' + enrichment_id = 'testString' # Invoke method - response = _service.delete_training_query( + response = _service.get_enrichment( project_id, - query_id, + enrichment_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 204 + assert response.status_code == 200 + def test_get_enrichment_all_params_with_retries(self): + # Enable retries and run test_get_enrichment_all_params. + _service.enable_retries() + self.test_get_enrichment_all_params() + + # Disable retries and run test_get_enrichment_all_params. + _service.disable_retries() + self.test_get_enrichment_all_params() @responses.activate - def test_delete_training_query_value_error(self): + def test_get_enrichment_value_error(self): """ - test_delete_training_query_value_error() + test_get_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' + responses.add(responses.GET, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' - query_id = 'testString' + enrichment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "query_id": query_id, + "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_training_query(**req_copy) - - + _service.get_enrichment(**req_copy) -# endregion -############################################################################## -# End of Service: TrainingData -############################################################################## + def test_get_enrichment_value_error_with_retries(self): + # Enable retries and run test_get_enrichment_value_error. + _service.enable_retries() + self.test_get_enrichment_value_error() -############################################################################## -# Start of Service: Analyze -############################################################################## -# region + # Disable retries and run test_get_enrichment_value_error. + _service.disable_retries() + self.test_get_enrichment_value_error() -class TestAnalyzeDocument(): +class TestUpdateEnrichment(): """ - Test Class for analyze_document + Test Class for update_enrichment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_analyze_document_all_params(self): + def test_update_enrichment_all_params(self): """ - analyze_document() + update_enrichment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, @@ -2095,36 +3849,44 @@ def test_analyze_document_all_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' + enrichment_id = 'testString' + name = 'testString' + description = 'testString' # Invoke method - response = _service.analyze_document( + response = _service.update_enrichment( project_id, - collection_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, + enrichment_id, + name, + description=description, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + def test_update_enrichment_all_params_with_retries(self): + # Enable retries and run test_update_enrichment_all_params. + _service.enable_retries() + self.test_update_enrichment_all_params() + + # Disable retries and run test_update_enrichment_all_params. + _service.disable_retries() + self.test_update_enrichment_all_params() @responses.activate - def test_analyze_document_required_params(self): + def test_update_enrichment_value_error(self): """ - test_analyze_document_required_params() + test_update_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, @@ -2133,84 +3895,127 @@ def test_analyze_document_required_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' + enrichment_id = 'testString' + name = 'testString' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "enrichment_id": enrichment_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_enrichment(**req_copy) + + def test_update_enrichment_value_error_with_retries(self): + # Enable retries and run test_update_enrichment_value_error. + _service.enable_retries() + self.test_update_enrichment_value_error() + + # Disable retries and run test_update_enrichment_value_error. + _service.disable_retries() + self.test_update_enrichment_value_error() + +class TestDeleteEnrichment(): + """ + Test Class for delete_enrichment + """ + + @responses.activate + def test_delete_enrichment_all_params(self): + """ + delete_enrichment() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/enrichments/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' # Invoke method - response = _service.analyze_document( + response = _service.delete_enrichment( project_id, - collection_id, + enrichment_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 204 + + def test_delete_enrichment_all_params_with_retries(self): + # Enable retries and run test_delete_enrichment_all_params. + _service.enable_retries() + self.test_delete_enrichment_all_params() + # Disable retries and run test_delete_enrichment_all_params. + _service.disable_retries() + self.test_delete_enrichment_all_params() @responses.activate - def test_analyze_document_value_error(self): + def test_delete_enrichment_value_error(self): """ - test_analyze_document_value_error() + test_delete_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/enrichments/testString') + responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200) + status=204) # Set up parameter values project_id = 'testString' - collection_id = 'testString' + enrichment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "collection_id": collection_id, + "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.analyze_document(**req_copy) + _service.delete_enrichment(**req_copy) + def test_delete_enrichment_value_error_with_retries(self): + # Enable retries and run test_delete_enrichment_value_error. + _service.enable_retries() + self.test_delete_enrichment_value_error() + # Disable retries and run test_delete_enrichment_value_error. + _service.disable_retries() + self.test_delete_enrichment_value_error() # endregion ############################################################################## -# End of Service: Analyze +# End of Service: Enrichments ############################################################################## ############################################################################## -# Start of Service: Enrichments +# Start of Service: DocumentClassifiers ############################################################################## # region -class TestListEnrichments(): +class TestListDocumentClassifiers(): """ - Test Class for list_enrichments + Test Class for list_document_classifiers """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_enrichments_all_params(self): + def test_list_document_classifiers_all_params(self): """ - list_enrichments() + list_document_classifiers() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -2221,7 +4026,7 @@ def test_list_enrichments_all_params(self): project_id = 'testString' # Invoke method - response = _service.list_enrichments( + response = _service.list_document_classifiers( project_id, headers={} ) @@ -2230,15 +4035,23 @@ def test_list_enrichments_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_document_classifiers_all_params_with_retries(self): + # Enable retries and run test_list_document_classifiers_all_params. + _service.enable_retries() + self.test_list_document_classifiers_all_params() + + # Disable retries and run test_list_document_classifiers_all_params. + _service.disable_retries() + self.test_list_document_classifiers_all_params() @responses.activate - def test_list_enrichments_value_error(self): + def test_list_document_classifiers_value_error(self): """ - test_list_enrichments_value_error() + test_list_document_classifiers_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -2255,64 +4068,66 @@ def test_list_enrichments_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_enrichments(**req_copy) + _service.list_document_classifiers(**req_copy) + def test_list_document_classifiers_value_error_with_retries(self): + # Enable retries and run test_list_document_classifiers_value_error. + _service.enable_retries() + self.test_list_document_classifiers_value_error() + # Disable retries and run test_list_document_classifiers_value_error. + _service.disable_retries() + self.test_list_document_classifiers_value_error() -class TestCreateEnrichment(): +class TestCreateDocumentClassifier(): """ - Test Class for create_enrichment + Test Class for create_document_classifier """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_create_enrichment_all_params(self): + def test_create_document_classifier_all_params(self): """ - create_enrichment() + create_document_classifier() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['languages'] = ['testString'] - enrichment_options_model['entity_type'] = 'testString' - enrichment_options_model['regular_expression'] = 'testString' - enrichment_options_model['result_field'] = 'testString' + # Construct a dict representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model = {} + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CreateEnrichment model - create_enrichment_model = {} - create_enrichment_model['name'] = 'testString' - create_enrichment_model['description'] = 'testString' - create_enrichment_model['type'] = 'dictionary' - create_enrichment_model['options'] = enrichment_options_model + # Construct a dict representation of a ClassifierFederatedModel model + classifier_federated_model_model = {} + classifier_federated_model_model['field'] = 'testString' + + # Construct a dict representation of a CreateDocumentClassifier model + create_document_classifier_model = {} + create_document_classifier_model['name'] = 'testString' + create_document_classifier_model['description'] = 'testString' + create_document_classifier_model['language'] = 'en' + create_document_classifier_model['answer_field'] = 'testString' + create_document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model['federated_classification'] = classifier_federated_model_model # Set up parameter values project_id = 'testString' - enrichment = create_enrichment_model - file = io.BytesIO(b'This is a mock file.').getvalue() + training_data = io.BytesIO(b'This is a mock file.').getvalue() + classifier = create_document_classifier_model + test_data = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = _service.create_enrichment( + response = _service.create_document_classifier( project_id, - enrichment, - file=file, + training_data, + classifier, + test_data=test_data, headers={} ) @@ -2320,43 +4135,57 @@ def test_create_enrichment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_document_classifier_all_params_with_retries(self): + # Enable retries and run test_create_document_classifier_all_params. + _service.enable_retries() + self.test_create_document_classifier_all_params() + + # Disable retries and run test_create_document_classifier_all_params. + _service.disable_retries() + self.test_create_document_classifier_all_params() @responses.activate - def test_create_enrichment_required_params(self): + def test_create_document_classifier_required_params(self): """ - test_create_enrichment_required_params() + test_create_document_classifier_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['languages'] = ['testString'] - enrichment_options_model['entity_type'] = 'testString' - enrichment_options_model['regular_expression'] = 'testString' - enrichment_options_model['result_field'] = 'testString' + # Construct a dict representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model = {} + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CreateEnrichment model - create_enrichment_model = {} - create_enrichment_model['name'] = 'testString' - create_enrichment_model['description'] = 'testString' - create_enrichment_model['type'] = 'dictionary' - create_enrichment_model['options'] = enrichment_options_model + # Construct a dict representation of a ClassifierFederatedModel model + classifier_federated_model_model = {} + classifier_federated_model_model['field'] = 'testString' + + # Construct a dict representation of a CreateDocumentClassifier model + create_document_classifier_model = {} + create_document_classifier_model['name'] = 'testString' + create_document_classifier_model['description'] = 'testString' + create_document_classifier_model['language'] = 'en' + create_document_classifier_model['answer_field'] = 'testString' + create_document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model['federated_classification'] = classifier_federated_model_model # Set up parameter values project_id = 'testString' - enrichment = create_enrichment_model + training_data = io.BytesIO(b'This is a mock file.').getvalue() + classifier = create_document_classifier_model # Invoke method - response = _service.create_enrichment( + response = _service.create_document_classifier( project_id, - enrichment, + training_data, + classifier, headers={} ) @@ -2364,75 +4193,85 @@ def test_create_enrichment_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_document_classifier_required_params_with_retries(self): + # Enable retries and run test_create_document_classifier_required_params. + _service.enable_retries() + self.test_create_document_classifier_required_params() + + # Disable retries and run test_create_document_classifier_required_params. + _service.disable_retries() + self.test_create_document_classifier_required_params() @responses.activate - def test_create_enrichment_value_error(self): + def test_create_document_classifier_value_error(self): """ - test_create_enrichment_value_error() + test_create_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['languages'] = ['testString'] - enrichment_options_model['entity_type'] = 'testString' - enrichment_options_model['regular_expression'] = 'testString' - enrichment_options_model['result_field'] = 'testString' + # Construct a dict representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model = {} + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CreateEnrichment model - create_enrichment_model = {} - create_enrichment_model['name'] = 'testString' - create_enrichment_model['description'] = 'testString' - create_enrichment_model['type'] = 'dictionary' - create_enrichment_model['options'] = enrichment_options_model + # Construct a dict representation of a ClassifierFederatedModel model + classifier_federated_model_model = {} + classifier_federated_model_model['field'] = 'testString' + + # Construct a dict representation of a CreateDocumentClassifier model + create_document_classifier_model = {} + create_document_classifier_model['name'] = 'testString' + create_document_classifier_model['description'] = 'testString' + create_document_classifier_model['language'] = 'en' + create_document_classifier_model['answer_field'] = 'testString' + create_document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model['federated_classification'] = classifier_federated_model_model # Set up parameter values project_id = 'testString' - enrichment = create_enrichment_model + training_data = io.BytesIO(b'This is a mock file.').getvalue() + classifier = create_document_classifier_model # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment": enrichment, + "training_data": training_data, + "classifier": classifier, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_enrichment(**req_copy) + _service.create_document_classifier(**req_copy) + def test_create_document_classifier_value_error_with_retries(self): + # Enable retries and run test_create_document_classifier_value_error. + _service.enable_retries() + self.test_create_document_classifier_value_error() + # Disable retries and run test_create_document_classifier_value_error. + _service.disable_retries() + self.test_create_document_classifier_value_error() -class TestGetEnrichment(): +class TestGetDocumentClassifier(): """ - Test Class for get_enrichment + Test Class for get_document_classifier """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_get_enrichment_all_params(self): + def test_get_document_classifier_all_params(self): """ - get_enrichment() + get_document_classifier() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.GET, url, body=mock_response, @@ -2441,12 +4280,12 @@ def test_get_enrichment_all_params(self): # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Invoke method - response = _service.get_enrichment( + response = _service.get_document_classifier( project_id, - enrichment_id, + classifier_id, headers={} ) @@ -2454,15 +4293,23 @@ def test_get_enrichment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_document_classifier_all_params_with_retries(self): + # Enable retries and run test_get_document_classifier_all_params. + _service.enable_retries() + self.test_get_document_classifier_all_params() + + # Disable retries and run test_get_document_classifier_all_params. + _service.disable_retries() + self.test_get_document_classifier_all_params() @responses.activate - def test_get_enrichment_value_error(self): + def test_get_document_classifier_value_error(self): """ - test_get_enrichment_value_error() + test_get_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.GET, url, body=mock_response, @@ -2471,142 +4318,194 @@ def test_get_enrichment_value_error(self): # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment_id": enrichment_id, + "classifier_id": classifier_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_enrichment(**req_copy) + _service.get_document_classifier(**req_copy) + def test_get_document_classifier_value_error_with_retries(self): + # Enable retries and run test_get_document_classifier_value_error. + _service.enable_retries() + self.test_get_document_classifier_value_error() + # Disable retries and run test_get_document_classifier_value_error. + _service.disable_retries() + self.test_get_document_classifier_value_error() -class TestUpdateEnrichment(): +class TestUpdateDocumentClassifier(): """ - Test Class for update_enrichment + Test Class for update_document_classifier """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_update_document_classifier_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + update_document_classifier() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a UpdateDocumentClassifier model + update_document_classifier_model = {} + update_document_classifier_model['name'] = 'testString' + update_document_classifier_model['description'] = 'testString' + + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + classifier = update_document_classifier_model + training_data = io.BytesIO(b'This is a mock file.').getvalue() + test_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.update_document_classifier( + project_id, + classifier_id, + classifier, + training_data=training_data, + test_data=test_data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + def test_update_document_classifier_all_params_with_retries(self): + # Enable retries and run test_update_document_classifier_all_params. + _service.enable_retries() + self.test_update_document_classifier_all_params() + + # Disable retries and run test_update_document_classifier_all_params. + _service.disable_retries() + self.test_update_document_classifier_all_params() @responses.activate - def test_update_enrichment_all_params(self): + def test_update_document_classifier_required_params(self): """ - update_enrichment() + test_update_document_classifier_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) + + # Construct a dict representation of a UpdateDocumentClassifier model + update_document_classifier_model = {} + update_document_classifier_model['name'] = 'testString' + update_document_classifier_model['description'] = 'testString' # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' - name = 'testString' - description = 'testString' + classifier_id = 'testString' + classifier = update_document_classifier_model # Invoke method - response = _service.update_enrichment( + response = _service.update_document_classifier( project_id, - enrichment_id, - name, - description=description, + classifier_id, + classifier, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' + assert response.status_code == 201 + + def test_update_document_classifier_required_params_with_retries(self): + # Enable retries and run test_update_document_classifier_required_params. + _service.enable_retries() + self.test_update_document_classifier_required_params() + # Disable retries and run test_update_document_classifier_required_params. + _service.disable_retries() + self.test_update_document_classifier_required_params() @responses.activate - def test_update_enrichment_value_error(self): + def test_update_document_classifier_value_error(self): """ - test_update_enrichment_value_error() + test_update_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) + + # Construct a dict representation of a UpdateDocumentClassifier model + update_document_classifier_model = {} + update_document_classifier_model['name'] = 'testString' + update_document_classifier_model['description'] = 'testString' # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' - name = 'testString' - description = 'testString' + classifier_id = 'testString' + classifier = update_document_classifier_model # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment_id": enrichment_id, - "name": name, + "classifier_id": classifier_id, + "classifier": classifier, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_enrichment(**req_copy) + _service.update_document_classifier(**req_copy) + def test_update_document_classifier_value_error_with_retries(self): + # Enable retries and run test_update_document_classifier_value_error. + _service.enable_retries() + self.test_update_document_classifier_value_error() + # Disable retries and run test_update_document_classifier_value_error. + _service.disable_retries() + self.test_update_document_classifier_value_error() -class TestDeleteEnrichment(): +class TestDeleteDocumentClassifier(): """ - Test Class for delete_enrichment + Test Class for delete_document_classifier """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_delete_enrichment_all_params(self): + def test_delete_document_classifier_all_params(self): """ - delete_enrichment() + delete_document_classifier() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') responses.add(responses.DELETE, url, status=204) # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Invoke method - response = _service.delete_enrichment( + response = _service.delete_document_classifier( project_id, - enrichment_id, + classifier_id, headers={} ) @@ -2614,281 +4513,263 @@ def test_delete_enrichment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_document_classifier_all_params_with_retries(self): + # Enable retries and run test_delete_document_classifier_all_params. + _service.enable_retries() + self.test_delete_document_classifier_all_params() + + # Disable retries and run test_delete_document_classifier_all_params. + _service.disable_retries() + self.test_delete_document_classifier_all_params() @responses.activate - def test_delete_enrichment_value_error(self): + def test_delete_document_classifier_value_error(self): """ - test_delete_enrichment_value_error() + test_delete_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') responses.add(responses.DELETE, url, status=204) # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment_id": enrichment_id, + "classifier_id": classifier_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_enrichment(**req_copy) + _service.delete_document_classifier(**req_copy) + def test_delete_document_classifier_value_error_with_retries(self): + # Enable retries and run test_delete_document_classifier_value_error. + _service.enable_retries() + self.test_delete_document_classifier_value_error() + # Disable retries and run test_delete_document_classifier_value_error. + _service.disable_retries() + self.test_delete_document_classifier_value_error() # endregion ############################################################################## -# End of Service: Enrichments +# End of Service: DocumentClassifiers ############################################################################## ############################################################################## -# Start of Service: Projects +# Start of Service: DocumentClassifierModels ############################################################################## # region -class TestListProjects(): +class TestListDocumentClassifierModels(): """ - Test Class for list_projects + Test Class for list_document_classifier_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_projects_all_params(self): + def test_list_document_classifier_models_all_params(self): """ - list_projects() + list_document_classifier_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) - # Invoke method - response = _service.list_projects() + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + # Invoke method + response = _service.list_document_classifier_models( + project_id, + classifier_id, + headers={} + ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_document_classifier_models_all_params_with_retries(self): + # Enable retries and run test_list_document_classifier_models_all_params. + _service.enable_retries() + self.test_list_document_classifier_models_all_params() + + # Disable retries and run test_list_document_classifier_models_all_params. + _service.disable_retries() + self.test_list_document_classifier_models_all_params() @responses.activate - def test_list_projects_value_error(self): + def test_list_document_classifier_models_value_error(self): """ - test_list_projects_value_error() + test_list_document_classifier_models_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + # Pass in all but one required param and check for a ValueError req_param_dict = { + "project_id": project_id, + "classifier_id": classifier_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_projects(**req_copy) + _service.list_document_classifier_models(**req_copy) + def test_list_document_classifier_models_value_error_with_retries(self): + # Enable retries and run test_list_document_classifier_models_value_error. + _service.enable_retries() + self.test_list_document_classifier_models_value_error() + # Disable retries and run test_list_document_classifier_models_value_error. + _service.disable_retries() + self.test_list_document_classifier_models_value_error() -class TestCreateProject(): +class TestCreateDocumentClassifierModel(): """ - Test Class for create_project + Test Class for create_document_classifier_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_create_project_all_params(self): + def test_create_document_classifier_model_all_params(self): """ - create_project() + create_document_classifier_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Construct a dict representation of a DefaultQueryParamsPassages model - default_query_params_passages_model = {} - default_query_params_passages_model['enabled'] = True - default_query_params_passages_model['count'] = 38 - default_query_params_passages_model['fields'] = ['testString'] - default_query_params_passages_model['characters'] = 38 - default_query_params_passages_model['per_document'] = True - default_query_params_passages_model['max_per_document'] = 38 - - # Construct a dict representation of a DefaultQueryParamsTableResults model - default_query_params_table_results_model = {} - default_query_params_table_results_model['enabled'] = True - default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 - - # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model - default_query_params_suggested_refinements_model = {} - default_query_params_suggested_refinements_model['enabled'] = True - default_query_params_suggested_refinements_model['count'] = 38 - - # Construct a dict representation of a DefaultQueryParams model - default_query_params_model = {} - default_query_params_model['collection_ids'] = ['testString'] - default_query_params_model['passages'] = default_query_params_passages_model - default_query_params_model['table_results'] = default_query_params_table_results_model - default_query_params_model['aggregation'] = 'testString' - default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model - default_query_params_model['spelling_suggestions'] = True - default_query_params_model['highlight'] = True - default_query_params_model['count'] = 38 - default_query_params_model['sort'] = 'testString' - default_query_params_model['return'] = ['testString'] + status=201) # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' name = 'testString' - type = 'document_retrieval' - default_query_parameters = default_query_params_model + description = 'testString' + learning_rate = 0 + l1_regularization_strengths = [1.0E-6] + l2_regularization_strengths = [1.0E-6] + training_max_steps = 0 + improvement_ratio = 0 # Invoke method - response = _service.create_project( + response = _service.create_document_classifier_model( + project_id, + classifier_id, name, - type, - default_query_parameters=default_query_parameters, + description=description, + learning_rate=learning_rate, + l1_regularization_strengths=l1_regularization_strengths, + l2_regularization_strengths=l2_regularization_strengths, + training_max_steps=training_max_steps, + improvement_ratio=improvement_ratio, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['type'] == 'document_retrieval' - assert req_body['default_query_parameters'] == default_query_params_model + assert req_body['description'] == 'testString' + assert req_body['learning_rate'] == 0 + assert req_body['l1_regularization_strengths'] == [1.0E-6] + assert req_body['l2_regularization_strengths'] == [1.0E-6] + assert req_body['training_max_steps'] == 0 + assert req_body['improvement_ratio'] == 0 + + def test_create_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_create_document_classifier_model_all_params. + _service.enable_retries() + self.test_create_document_classifier_model_all_params() + # Disable retries and run test_create_document_classifier_model_all_params. + _service.disable_retries() + self.test_create_document_classifier_model_all_params() @responses.activate - def test_create_project_value_error(self): + def test_create_document_classifier_model_value_error(self): """ - test_create_project_value_error() + test_create_document_classifier_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Construct a dict representation of a DefaultQueryParamsPassages model - default_query_params_passages_model = {} - default_query_params_passages_model['enabled'] = True - default_query_params_passages_model['count'] = 38 - default_query_params_passages_model['fields'] = ['testString'] - default_query_params_passages_model['characters'] = 38 - default_query_params_passages_model['per_document'] = True - default_query_params_passages_model['max_per_document'] = 38 - - # Construct a dict representation of a DefaultQueryParamsTableResults model - default_query_params_table_results_model = {} - default_query_params_table_results_model['enabled'] = True - default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 - - # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model - default_query_params_suggested_refinements_model = {} - default_query_params_suggested_refinements_model['enabled'] = True - default_query_params_suggested_refinements_model['count'] = 38 - - # Construct a dict representation of a DefaultQueryParams model - default_query_params_model = {} - default_query_params_model['collection_ids'] = ['testString'] - default_query_params_model['passages'] = default_query_params_passages_model - default_query_params_model['table_results'] = default_query_params_table_results_model - default_query_params_model['aggregation'] = 'testString' - default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model - default_query_params_model['spelling_suggestions'] = True - default_query_params_model['highlight'] = True - default_query_params_model['count'] = 38 - default_query_params_model['sort'] = 'testString' - default_query_params_model['return'] = ['testString'] + status=201) # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' name = 'testString' - type = 'document_retrieval' - default_query_parameters = default_query_params_model + description = 'testString' + learning_rate = 0 + l1_regularization_strengths = [1.0E-6] + l2_regularization_strengths = [1.0E-6] + training_max_steps = 0 + improvement_ratio = 0 # Pass in all but one required param and check for a ValueError req_param_dict = { + "project_id": project_id, + "classifier_id": classifier_id, "name": name, - "type": type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_project(**req_copy) + _service.create_document_classifier_model(**req_copy) + def test_create_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_create_document_classifier_model_value_error. + _service.enable_retries() + self.test_create_document_classifier_model_value_error() + # Disable retries and run test_create_document_classifier_model_value_error. + _service.disable_retries() + self.test_create_document_classifier_model_value_error() -class TestGetProject(): +class TestGetDocumentClassifierModel(): """ - Test Class for get_project + Test Class for get_document_classifier_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_get_project_all_params(self): + def test_get_document_classifier_model_all_params(self): """ - get_project() + get_document_classifier_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2897,10 +4778,14 @@ def test_get_project_all_params(self): # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' # Invoke method - response = _service.get_project( + response = _service.get_document_classifier_model( project_id, + classifier_id, + model_id, headers={} ) @@ -2908,15 +4793,23 @@ def test_get_project_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_get_document_classifier_model_all_params. + _service.enable_retries() + self.test_get_document_classifier_model_all_params() + + # Disable retries and run test_get_document_classifier_model_all_params. + _service.disable_retries() + self.test_get_document_classifier_model_all_params() @responses.activate - def test_get_project_value_error(self): + def test_get_document_classifier_model_value_error(self): """ - test_get_project_value_error() + test_get_document_classifier_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2925,75 +4818,224 @@ def test_get_project_value_error(self): # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "classifier_id": classifier_id, + "model_id": model_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_project(**req_copy) + _service.get_document_classifier_model(**req_copy) + def test_get_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_get_document_classifier_model_value_error. + _service.enable_retries() + self.test_get_document_classifier_model_value_error() + # Disable retries and run test_get_document_classifier_model_value_error. + _service.disable_retries() + self.test_get_document_classifier_model_value_error() -class TestUpdateProject(): +class TestUpdateDocumentClassifierModel(): """ - Test Class for update_project + Test Class for update_document_classifier_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_update_project_all_params(self): + def test_update_document_classifier_model_all_params(self): """ - update_project() + update_document_classifier_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' name = 'testString' + description = 'testString' # Invoke method - response = _service.update_project( + response = _service.update_document_classifier_model( project_id, + classifier_id, + model_id, name=name, + description=description, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + + def test_update_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_update_document_classifier_model_all_params. + _service.enable_retries() + self.test_update_document_classifier_model_all_params() + + # Disable retries and run test_update_document_classifier_model_all_params. + _service.disable_retries() + self.test_update_document_classifier_model_all_params() + + @responses.activate + def test_update_document_classifier_model_value_error(self): + """ + test_update_document_classifier_model_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' + name = 'testString' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "classifier_id": classifier_id, + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_document_classifier_model(**req_copy) + + def test_update_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_update_document_classifier_model_value_error. + _service.enable_retries() + self.test_update_document_classifier_model_value_error() + + # Disable retries and run test_update_document_classifier_model_value_error. + _service.disable_retries() + self.test_update_document_classifier_model_value_error() + +class TestDeleteDocumentClassifierModel(): + """ + Test Class for delete_document_classifier_model + """ + + @responses.activate + def test_delete_document_classifier_model_all_params(self): + """ + delete_document_classifier_model() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' + + # Invoke method + response = _service.delete_document_classifier_model( + project_id, + classifier_id, + model_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_delete_document_classifier_model_all_params. + _service.enable_retries() + self.test_delete_document_classifier_model_all_params() + + # Disable retries and run test_delete_document_classifier_model_all_params. + _service.disable_retries() + self.test_delete_document_classifier_model_all_params() + + @responses.activate + def test_delete_document_classifier_model_value_error(self): + """ + test_delete_document_classifier_model_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "classifier_id": classifier_id, + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_document_classifier_model(**req_copy) + + def test_delete_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_delete_document_classifier_model_value_error. + _service.enable_retries() + self.test_delete_document_classifier_model_value_error() + + # Disable retries and run test_delete_document_classifier_model_value_error. + _service.disable_retries() + self.test_delete_document_classifier_model_value_error() + +# endregion +############################################################################## +# End of Service: DocumentClassifierModels +############################################################################## +############################################################################## +# Start of Service: Analyze +############################################################################## +# region + +class TestAnalyzeDocument(): + """ + Test Class for analyze_document + """ @responses.activate - def test_update_project_required_params(self): + def test_analyze_document_all_params(self): """ - test_update_project_required_params() + analyze_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -3002,10 +5044,20 @@ def test_update_project_required_params(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' # Invoke method - response = _service.update_project( + response = _service.analyze_document( project_id, + collection_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, headers={} ) @@ -3013,15 +5065,23 @@ def test_update_project_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_analyze_document_all_params_with_retries(self): + # Enable retries and run test_analyze_document_all_params. + _service.enable_retries() + self.test_analyze_document_all_params() + + # Disable retries and run test_analyze_document_all_params. + _service.disable_retries() + self.test_analyze_document_all_params() @responses.activate - def test_update_project_value_error(self): + def test_analyze_document_required_params(self): """ - test_update_project_value_error() + test_analyze_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -3030,87 +5090,68 @@ def test_update_project_value_error(self): # Set up parameter values project_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "project_id": project_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_project(**req_copy) - - - -class TestDeleteProject(): - """ - Test Class for delete_project - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_project_all_params(self): - """ - delete_project() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - responses.add(responses.DELETE, - url, - status=204) - - # Set up parameter values - project_id = 'testString' + collection_id = 'testString' # Invoke method - response = _service.delete_project( + response = _service.analyze_document( project_id, + collection_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 204 + assert response.status_code == 200 + def test_analyze_document_required_params_with_retries(self): + # Enable retries and run test_analyze_document_required_params. + _service.enable_retries() + self.test_analyze_document_required_params() + + # Disable retries and run test_analyze_document_required_params. + _service.disable_retries() + self.test_analyze_document_required_params() @responses.activate - def test_delete_project_value_error(self): + def test_analyze_document_value_error(self): """ - test_delete_project_value_error() + test_analyze_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' + responses.add(responses.POST, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "collection_id": collection_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_project(**req_copy) + _service.analyze_document(**req_copy) + def test_analyze_document_value_error_with_retries(self): + # Enable retries and run test_analyze_document_value_error. + _service.enable_retries() + self.test_analyze_document_value_error() + # Disable retries and run test_analyze_document_value_error. + _service.disable_retries() + self.test_analyze_document_value_error() # endregion ############################################################################## -# End of Service: Projects +# End of Service: Analyze ############################################################################## ############################################################################## @@ -3123,24 +5164,13 @@ class TestDeleteUserData(): Test Class for delete_user_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_user_data_all_params(self): """ delete_user_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/user_data') + url = preprocess_url('/v2/user_data') responses.add(responses.DELETE, url, status=200) @@ -3162,6 +5192,14 @@ def test_delete_user_data_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. + _service.enable_retries() + self.test_delete_user_data_all_params() + + # Disable retries and run test_delete_user_data_all_params. + _service.disable_retries() + self.test_delete_user_data_all_params() @responses.activate def test_delete_user_data_value_error(self): @@ -3169,7 +5207,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/user_data') + url = preprocess_url('/v2/user_data') responses.add(responses.DELETE, url, status=200) @@ -3186,7 +5224,14 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. + _service.enable_retries() + self.test_delete_user_data_value_error() + # Disable retries and run test_delete_user_data_value_error. + _service.disable_retries() + self.test_delete_user_data_value_error() # endregion ############################################################################## @@ -3211,18 +5256,10 @@ def test_analyzed_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = "2019-01-01T12:00:00Z" - notice_model['document_id'] = 'testString' - notice_model['collection_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' analyzed_result_model = {} # AnalyzedResult - analyzed_result_model['metadata'] = {} - analyzed_result_model['foo'] = { 'foo': 'bar' } + analyzed_result_model['metadata'] = {'foo': 'bar'} + analyzed_result_model['foo'] = 'testString' # Construct a json representation of a AnalyzedDocument model analyzed_document_model_json = {} @@ -3256,8 +5293,8 @@ def test_analyzed_result_serialization(self): # Construct a json representation of a AnalyzedResult model analyzed_result_model_json = {} - analyzed_result_model_json['metadata'] = {} - analyzed_result_model_json['foo'] = { 'foo': 'bar' } + analyzed_result_model_json['metadata'] = {'foo': 'bar'} + analyzed_result_model_json['foo'] = 'testString' # Construct a model instance of AnalyzedResult by calling from_dict on the json representation analyzed_result_model = AnalyzedResult.from_dict(analyzed_result_model_json) @@ -3279,11 +5316,89 @@ def test_analyzed_result_serialization(self): actual_dict = analyzed_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': 'testString'} analyzed_result_model.set_properties(expected_dict) actual_dict = analyzed_result_model.get_properties() assert actual_dict == expected_dict +class TestModel_ClassifierFederatedModel(): + """ + Test Class for ClassifierFederatedModel + """ + + def test_classifier_federated_model_serialization(self): + """ + Test serialization/deserialization for ClassifierFederatedModel + """ + + # Construct a json representation of a ClassifierFederatedModel model + classifier_federated_model_model_json = {} + classifier_federated_model_model_json['field'] = 'testString' + + # Construct a model instance of ClassifierFederatedModel by calling from_dict on the json representation + classifier_federated_model_model = ClassifierFederatedModel.from_dict(classifier_federated_model_model_json) + assert classifier_federated_model_model != False + + # Construct a model instance of ClassifierFederatedModel by calling from_dict on the json representation + classifier_federated_model_model_dict = ClassifierFederatedModel.from_dict(classifier_federated_model_model_json).__dict__ + classifier_federated_model_model2 = ClassifierFederatedModel(**classifier_federated_model_model_dict) + + # Verify the model instances are equivalent + assert classifier_federated_model_model == classifier_federated_model_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_federated_model_model_json2 = classifier_federated_model_model.to_dict() + assert classifier_federated_model_model_json2 == classifier_federated_model_model_json + +class TestModel_ClassifierModelEvaluation(): + """ + Test Class for ClassifierModelEvaluation + """ + + def test_classifier_model_evaluation_serialization(self): + """ + Test serialization/deserialization for ClassifierModelEvaluation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model['precision'] = 0 + model_evaluation_micro_average_model['recall'] = 0 + model_evaluation_micro_average_model['f1'] = 0 + + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model['precision'] = 0 + model_evaluation_macro_average_model['recall'] = 0 + model_evaluation_macro_average_model['f1'] = 0 + + per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model['name'] = 'testString' + per_class_model_evaluation_model['precision'] = 0 + per_class_model_evaluation_model['recall'] = 0 + per_class_model_evaluation_model['f1'] = 0 + + # Construct a json representation of a ClassifierModelEvaluation model + classifier_model_evaluation_model_json = {} + classifier_model_evaluation_model_json['micro_average'] = model_evaluation_micro_average_model + classifier_model_evaluation_model_json['macro_average'] = model_evaluation_macro_average_model + classifier_model_evaluation_model_json['per_class'] = [per_class_model_evaluation_model] + + # Construct a model instance of ClassifierModelEvaluation by calling from_dict on the json representation + classifier_model_evaluation_model = ClassifierModelEvaluation.from_dict(classifier_model_evaluation_model_json) + assert classifier_model_evaluation_model != False + + # Construct a model instance of ClassifierModelEvaluation by calling from_dict on the json representation + classifier_model_evaluation_model_dict = ClassifierModelEvaluation.from_dict(classifier_model_evaluation_model_json).__dict__ + classifier_model_evaluation_model2 = ClassifierModelEvaluation(**classifier_model_evaluation_model_dict) + + # Verify the model instances are equivalent + assert classifier_model_evaluation_model == classifier_model_evaluation_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_model_evaluation_model_json2 = classifier_model_evaluation_model.to_dict() + assert classifier_model_evaluation_model_json2 == classifier_model_evaluation_model_json + class TestModel_Collection(): """ Test Class for Collection @@ -3296,7 +5411,6 @@ def test_collection_serialization(self): # Construct a json representation of a Collection model collection_model_json = {} - collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' # Construct a model instance of Collection by calling from_dict on the json representation @@ -3332,10 +5446,8 @@ def test_collection_details_serialization(self): # Construct a json representation of a CollectionDetails model collection_details_model_json = {} - collection_details_model_json['collection_id'] = 'testString' collection_details_model_json['name'] = 'testString' collection_details_model_json['description'] = 'testString' - collection_details_model_json['created'] = "2019-01-01T12:00:00Z" collection_details_model_json['language'] = 'en' collection_details_model_json['enrichments'] = [collection_enrichment_model] @@ -3354,6 +5466,36 @@ def test_collection_details_serialization(self): collection_details_model_json2 = collection_details_model.to_dict() assert collection_details_model_json2 == collection_details_model_json +class TestModel_CollectionDetailsSmartDocumentUnderstanding(): + """ + Test Class for CollectionDetailsSmartDocumentUnderstanding + """ + + def test_collection_details_smart_document_understanding_serialization(self): + """ + Test serialization/deserialization for CollectionDetailsSmartDocumentUnderstanding + """ + + # Construct a json representation of a CollectionDetailsSmartDocumentUnderstanding model + collection_details_smart_document_understanding_model_json = {} + collection_details_smart_document_understanding_model_json['enabled'] = True + collection_details_smart_document_understanding_model_json['model'] = 'custom' + + # Construct a model instance of CollectionDetailsSmartDocumentUnderstanding by calling from_dict on the json representation + collection_details_smart_document_understanding_model = CollectionDetailsSmartDocumentUnderstanding.from_dict(collection_details_smart_document_understanding_model_json) + assert collection_details_smart_document_understanding_model != False + + # Construct a model instance of CollectionDetailsSmartDocumentUnderstanding by calling from_dict on the json representation + collection_details_smart_document_understanding_model_dict = CollectionDetailsSmartDocumentUnderstanding.from_dict(collection_details_smart_document_understanding_model_json).__dict__ + collection_details_smart_document_understanding_model2 = CollectionDetailsSmartDocumentUnderstanding(**collection_details_smart_document_understanding_model_dict) + + # Verify the model instances are equivalent + assert collection_details_smart_document_understanding_model == collection_details_smart_document_understanding_model2 + + # Convert model instance back to dict and verify no loss of data + collection_details_smart_document_understanding_model_json2 = collection_details_smart_document_understanding_model.to_dict() + assert collection_details_smart_document_understanding_model_json2 == collection_details_smart_document_understanding_model_json + class TestModel_CollectionEnrichment(): """ Test Class for CollectionEnrichment @@ -3595,6 +5737,49 @@ def test_component_settings_response_serialization(self): component_settings_response_model_json2 = component_settings_response_model.to_dict() assert component_settings_response_model_json2 == component_settings_response_model_json +class TestModel_CreateDocumentClassifier(): + """ + Test Class for CreateDocumentClassifier + """ + + def test_create_document_classifier_serialization(self): + """ + Test serialization/deserialization for CreateDocumentClassifier + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] + + classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model['field'] = 'testString' + + # Construct a json representation of a CreateDocumentClassifier model + create_document_classifier_model_json = {} + create_document_classifier_model_json['name'] = 'testString' + create_document_classifier_model_json['description'] = 'testString' + create_document_classifier_model_json['language'] = 'en' + create_document_classifier_model_json['answer_field'] = 'testString' + create_document_classifier_model_json['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model_json['federated_classification'] = classifier_federated_model_model + + # Construct a model instance of CreateDocumentClassifier by calling from_dict on the json representation + create_document_classifier_model = CreateDocumentClassifier.from_dict(create_document_classifier_model_json) + assert create_document_classifier_model != False + + # Construct a model instance of CreateDocumentClassifier by calling from_dict on the json representation + create_document_classifier_model_dict = CreateDocumentClassifier.from_dict(create_document_classifier_model_json).__dict__ + create_document_classifier_model2 = CreateDocumentClassifier(**create_document_classifier_model_dict) + + # Verify the model instances are equivalent + assert create_document_classifier_model == create_document_classifier_model2 + + # Convert model instance back to dict and verify no loss of data + create_document_classifier_model_json2 = create_document_classifier_model.to_dict() + assert create_document_classifier_model_json2 == create_document_classifier_model_json + class TestModel_CreateEnrichment(): """ Test Class for CreateEnrichment @@ -3612,12 +5797,16 @@ def test_create_enrichment_serialization(self): enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 # Construct a json representation of a CreateEnrichment model create_enrichment_model_json = {} create_enrichment_model_json['name'] = 'testString' create_enrichment_model_json['description'] = 'testString' - create_enrichment_model_json['type'] = 'dictionary' + create_enrichment_model_json['type'] = 'classifier' create_enrichment_model_json['options'] = enrichment_options_model # Construct a model instance of CreateEnrichment by calling from_dict on the json representation @@ -3878,11 +6067,327 @@ def test_document_attribute_serialization(self): document_attribute_model2 = DocumentAttribute(**document_attribute_model_dict) # Verify the model instances are equivalent - assert document_attribute_model == document_attribute_model2 + assert document_attribute_model == document_attribute_model2 + + # Convert model instance back to dict and verify no loss of data + document_attribute_model_json2 = document_attribute_model.to_dict() + assert document_attribute_model_json2 == document_attribute_model_json + +class TestModel_DocumentClassifier(): + """ + Test Class for DocumentClassifier + """ + + def test_document_classifier_serialization(self): + """ + Test serialization/deserialization for DocumentClassifier + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] + + classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model['field'] = 'testString' + + # Construct a json representation of a DocumentClassifier model + document_classifier_model_json = {} + document_classifier_model_json['name'] = 'testString' + document_classifier_model_json['description'] = 'testString' + document_classifier_model_json['language'] = 'en' + document_classifier_model_json['enrichments'] = [document_classifier_enrichment_model] + document_classifier_model_json['recognized_fields'] = ['testString'] + document_classifier_model_json['answer_field'] = 'testString' + document_classifier_model_json['training_data_file'] = 'testString' + document_classifier_model_json['test_data_file'] = 'testString' + document_classifier_model_json['federated_classification'] = classifier_federated_model_model + + # Construct a model instance of DocumentClassifier by calling from_dict on the json representation + document_classifier_model = DocumentClassifier.from_dict(document_classifier_model_json) + assert document_classifier_model != False + + # Construct a model instance of DocumentClassifier by calling from_dict on the json representation + document_classifier_model_dict = DocumentClassifier.from_dict(document_classifier_model_json).__dict__ + document_classifier_model2 = DocumentClassifier(**document_classifier_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_model == document_classifier_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_model_json2 = document_classifier_model.to_dict() + assert document_classifier_model_json2 == document_classifier_model_json + +class TestModel_DocumentClassifierEnrichment(): + """ + Test Class for DocumentClassifierEnrichment + """ + + def test_document_classifier_enrichment_serialization(self): + """ + Test serialization/deserialization for DocumentClassifierEnrichment + """ + + # Construct a json representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model_json = {} + document_classifier_enrichment_model_json['enrichment_id'] = 'testString' + document_classifier_enrichment_model_json['fields'] = ['testString'] + + # Construct a model instance of DocumentClassifierEnrichment by calling from_dict on the json representation + document_classifier_enrichment_model = DocumentClassifierEnrichment.from_dict(document_classifier_enrichment_model_json) + assert document_classifier_enrichment_model != False + + # Construct a model instance of DocumentClassifierEnrichment by calling from_dict on the json representation + document_classifier_enrichment_model_dict = DocumentClassifierEnrichment.from_dict(document_classifier_enrichment_model_json).__dict__ + document_classifier_enrichment_model2 = DocumentClassifierEnrichment(**document_classifier_enrichment_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_enrichment_model == document_classifier_enrichment_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_enrichment_model_json2 = document_classifier_enrichment_model.to_dict() + assert document_classifier_enrichment_model_json2 == document_classifier_enrichment_model_json + +class TestModel_DocumentClassifierModel(): + """ + Test Class for DocumentClassifierModel + """ + + def test_document_classifier_model_serialization(self): + """ + Test serialization/deserialization for DocumentClassifierModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model['precision'] = 0 + model_evaluation_micro_average_model['recall'] = 0 + model_evaluation_micro_average_model['f1'] = 0 + + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model['precision'] = 0 + model_evaluation_macro_average_model['recall'] = 0 + model_evaluation_macro_average_model['f1'] = 0 + + per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model['name'] = 'testString' + per_class_model_evaluation_model['precision'] = 0 + per_class_model_evaluation_model['recall'] = 0 + per_class_model_evaluation_model['f1'] = 0 + + classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model + classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model + classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] + + # Construct a json representation of a DocumentClassifierModel model + document_classifier_model_model_json = {} + document_classifier_model_model_json['name'] = 'testString' + document_classifier_model_model_json['description'] = 'testString' + document_classifier_model_model_json['training_data_file'] = 'testString' + document_classifier_model_model_json['test_data_file'] = 'testString' + document_classifier_model_model_json['status'] = 'training' + document_classifier_model_model_json['evaluation'] = classifier_model_evaluation_model + document_classifier_model_model_json['enrichment_id'] = 'testString' + + # Construct a model instance of DocumentClassifierModel by calling from_dict on the json representation + document_classifier_model_model = DocumentClassifierModel.from_dict(document_classifier_model_model_json) + assert document_classifier_model_model != False + + # Construct a model instance of DocumentClassifierModel by calling from_dict on the json representation + document_classifier_model_model_dict = DocumentClassifierModel.from_dict(document_classifier_model_model_json).__dict__ + document_classifier_model_model2 = DocumentClassifierModel(**document_classifier_model_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_model_model == document_classifier_model_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_model_model_json2 = document_classifier_model_model.to_dict() + assert document_classifier_model_model_json2 == document_classifier_model_model_json + +class TestModel_DocumentClassifierModels(): + """ + Test Class for DocumentClassifierModels + """ + + def test_document_classifier_models_serialization(self): + """ + Test serialization/deserialization for DocumentClassifierModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model['precision'] = 0 + model_evaluation_micro_average_model['recall'] = 0 + model_evaluation_micro_average_model['f1'] = 0 + + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model['precision'] = 0 + model_evaluation_macro_average_model['recall'] = 0 + model_evaluation_macro_average_model['f1'] = 0 + + per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model['name'] = 'testString' + per_class_model_evaluation_model['precision'] = 0 + per_class_model_evaluation_model['recall'] = 0 + per_class_model_evaluation_model['f1'] = 0 + + classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model + classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model + classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] + + document_classifier_model_model = {} # DocumentClassifierModel + document_classifier_model_model['name'] = 'testString' + document_classifier_model_model['description'] = 'testString' + document_classifier_model_model['training_data_file'] = 'testString' + document_classifier_model_model['test_data_file'] = 'testString' + document_classifier_model_model['status'] = 'training' + document_classifier_model_model['evaluation'] = classifier_model_evaluation_model + document_classifier_model_model['enrichment_id'] = 'testString' + + # Construct a json representation of a DocumentClassifierModels model + document_classifier_models_model_json = {} + document_classifier_models_model_json['models'] = [document_classifier_model_model] + + # Construct a model instance of DocumentClassifierModels by calling from_dict on the json representation + document_classifier_models_model = DocumentClassifierModels.from_dict(document_classifier_models_model_json) + assert document_classifier_models_model != False + + # Construct a model instance of DocumentClassifierModels by calling from_dict on the json representation + document_classifier_models_model_dict = DocumentClassifierModels.from_dict(document_classifier_models_model_json).__dict__ + document_classifier_models_model2 = DocumentClassifierModels(**document_classifier_models_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_models_model == document_classifier_models_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_models_model_json2 = document_classifier_models_model.to_dict() + assert document_classifier_models_model_json2 == document_classifier_models_model_json + +class TestModel_DocumentClassifiers(): + """ + Test Class for DocumentClassifiers + """ + + def test_document_classifiers_serialization(self): + """ + Test serialization/deserialization for DocumentClassifiers + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] + + classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model['field'] = 'testString' + + document_classifier_model = {} # DocumentClassifier + document_classifier_model['name'] = 'testString' + document_classifier_model['description'] = 'testString' + document_classifier_model['language'] = 'en' + document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + document_classifier_model['recognized_fields'] = ['testString'] + document_classifier_model['answer_field'] = 'testString' + document_classifier_model['training_data_file'] = 'testString' + document_classifier_model['test_data_file'] = 'testString' + document_classifier_model['federated_classification'] = classifier_federated_model_model + + # Construct a json representation of a DocumentClassifiers model + document_classifiers_model_json = {} + document_classifiers_model_json['classifiers'] = [document_classifier_model] + + # Construct a model instance of DocumentClassifiers by calling from_dict on the json representation + document_classifiers_model = DocumentClassifiers.from_dict(document_classifiers_model_json) + assert document_classifiers_model != False + + # Construct a model instance of DocumentClassifiers by calling from_dict on the json representation + document_classifiers_model_dict = DocumentClassifiers.from_dict(document_classifiers_model_json).__dict__ + document_classifiers_model2 = DocumentClassifiers(**document_classifiers_model_dict) + + # Verify the model instances are equivalent + assert document_classifiers_model == document_classifiers_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifiers_model_json2 = document_classifiers_model.to_dict() + assert document_classifiers_model_json2 == document_classifiers_model_json + +class TestModel_DocumentDetails(): + """ + Test Class for DocumentDetails + """ + + def test_document_details_serialization(self): + """ + Test serialization/deserialization for DocumentDetails + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + + document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model['have_notices'] = True + document_details_children_model['count'] = 38 + + # Construct a json representation of a DocumentDetails model + document_details_model_json = {} + document_details_model_json['status'] = 'available' + document_details_model_json['notices'] = [notice_model] + document_details_model_json['children'] = document_details_children_model + document_details_model_json['filename'] = 'testString' + document_details_model_json['file_type'] = 'testString' + document_details_model_json['sha256'] = 'testString' + + # Construct a model instance of DocumentDetails by calling from_dict on the json representation + document_details_model = DocumentDetails.from_dict(document_details_model_json) + assert document_details_model != False + + # Construct a model instance of DocumentDetails by calling from_dict on the json representation + document_details_model_dict = DocumentDetails.from_dict(document_details_model_json).__dict__ + document_details_model2 = DocumentDetails(**document_details_model_dict) + + # Verify the model instances are equivalent + assert document_details_model == document_details_model2 + + # Convert model instance back to dict and verify no loss of data + document_details_model_json2 = document_details_model.to_dict() + assert document_details_model_json2 == document_details_model_json + +class TestModel_DocumentDetailsChildren(): + """ + Test Class for DocumentDetailsChildren + """ + + def test_document_details_children_serialization(self): + """ + Test serialization/deserialization for DocumentDetailsChildren + """ + + # Construct a json representation of a DocumentDetailsChildren model + document_details_children_model_json = {} + document_details_children_model_json['have_notices'] = True + document_details_children_model_json['count'] = 38 + + # Construct a model instance of DocumentDetailsChildren by calling from_dict on the json representation + document_details_children_model = DocumentDetailsChildren.from_dict(document_details_children_model_json) + assert document_details_children_model != False + + # Construct a model instance of DocumentDetailsChildren by calling from_dict on the json representation + document_details_children_model_dict = DocumentDetailsChildren.from_dict(document_details_children_model_json).__dict__ + document_details_children_model2 = DocumentDetailsChildren(**document_details_children_model_dict) + + # Verify the model instances are equivalent + assert document_details_children_model == document_details_children_model2 # Convert model instance back to dict and verify no loss of data - document_attribute_model_json2 = document_attribute_model.to_dict() - assert document_attribute_model_json2 == document_attribute_model_json + document_details_children_model_json2 = document_details_children_model.to_dict() + assert document_details_children_model_json2 == document_details_children_model_json class TestModel_Enrichment(): """ @@ -3901,10 +6406,13 @@ def test_enrichment_serialization(self): enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 # Construct a json representation of a Enrichment model enrichment_model_json = {} - enrichment_model_json['enrichment_id'] = 'testString' enrichment_model_json['name'] = 'testString' enrichment_model_json['description'] = 'testString' enrichment_model_json['type'] = 'part_of_speech' @@ -3941,6 +6449,10 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json['entity_type'] = 'testString' enrichment_options_model_json['regular_expression'] = 'testString' enrichment_options_model_json['result_field'] = 'testString' + enrichment_options_model_json['classifier_id'] = 'testString' + enrichment_options_model_json['model_id'] = 'testString' + enrichment_options_model_json['confidence_threshold'] = 0 + enrichment_options_model_json['top_k'] = 38 # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) @@ -3974,9 +6486,12 @@ def test_enrichments_serialization(self): enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 enrichment_model = {} # Enrichment - enrichment_model['enrichment_id'] = 'testString' enrichment_model['name'] = 'testString' enrichment_model['description'] = 'testString' enrichment_model['type'] = 'part_of_speech' @@ -4001,6 +6516,71 @@ def test_enrichments_serialization(self): enrichments_model_json2 = enrichments_model.to_dict() assert enrichments_model_json2 == enrichments_model_json +class TestModel_Expansion(): + """ + Test Class for Expansion + """ + + def test_expansion_serialization(self): + """ + Test serialization/deserialization for Expansion + """ + + # Construct a json representation of a Expansion model + expansion_model_json = {} + expansion_model_json['input_terms'] = ['testString'] + expansion_model_json['expanded_terms'] = ['testString'] + + # Construct a model instance of Expansion by calling from_dict on the json representation + expansion_model = Expansion.from_dict(expansion_model_json) + assert expansion_model != False + + # Construct a model instance of Expansion by calling from_dict on the json representation + expansion_model_dict = Expansion.from_dict(expansion_model_json).__dict__ + expansion_model2 = Expansion(**expansion_model_dict) + + # Verify the model instances are equivalent + assert expansion_model == expansion_model2 + + # Convert model instance back to dict and verify no loss of data + expansion_model_json2 = expansion_model.to_dict() + assert expansion_model_json2 == expansion_model_json + +class TestModel_Expansions(): + """ + Test Class for Expansions + """ + + def test_expansions_serialization(self): + """ + Test serialization/deserialization for Expansions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + expansion_model = {} # Expansion + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] + + # Construct a json representation of a Expansions model + expansions_model_json = {} + expansions_model_json['expansions'] = [expansion_model] + + # Construct a model instance of Expansions by calling from_dict on the json representation + expansions_model = Expansions.from_dict(expansions_model_json) + assert expansions_model != False + + # Construct a model instance of Expansions by calling from_dict on the json representation + expansions_model_dict = Expansions.from_dict(expansions_model_json).__dict__ + expansions_model2 = Expansions(**expansions_model_dict) + + # Verify the model instances are equivalent + assert expansions_model == expansions_model2 + + # Convert model instance back to dict and verify no loss of data + expansions_model_json2 = expansions_model.to_dict() + assert expansions_model_json2 == expansions_model_json + class TestModel_Field(): """ Test Class for Field @@ -4013,9 +6593,6 @@ def test_field_serialization(self): # Construct a json representation of a Field model field_model_json = {} - field_model_json['field'] = 'testString' - field_model_json['type'] = 'nested' - field_model_json['collection_id'] = 'testString' # Construct a model instance of Field by calling from_dict on the json representation field_model = Field.from_dict(field_model_json) @@ -4045,7 +6622,6 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. collection_model = {} # Collection - collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' collection_model['name'] = 'example' # Construct a json representation of a ListCollectionsResponse model @@ -4067,6 +6643,52 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json +class TestModel_ListDocumentsResponse(): + """ + Test Class for ListDocumentsResponse + """ + + def test_list_documents_response_serialization(self): + """ + Test serialization/deserialization for ListDocumentsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + + document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model['have_notices'] = True + document_details_children_model['count'] = 38 + + document_details_model = {} # DocumentDetails + document_details_model['status'] = 'available' + document_details_model['notices'] = [notice_model] + document_details_model['children'] = document_details_children_model + document_details_model['filename'] = 'testString' + document_details_model['file_type'] = 'testString' + document_details_model['sha256'] = 'testString' + + # Construct a json representation of a ListDocumentsResponse model + list_documents_response_model_json = {} + list_documents_response_model_json['matching_results'] = 38 + list_documents_response_model_json['documents'] = [document_details_model] + + # Construct a model instance of ListDocumentsResponse by calling from_dict on the json representation + list_documents_response_model = ListDocumentsResponse.from_dict(list_documents_response_model_json) + assert list_documents_response_model != False + + # Construct a model instance of ListDocumentsResponse by calling from_dict on the json representation + list_documents_response_model_dict = ListDocumentsResponse.from_dict(list_documents_response_model_json).__dict__ + list_documents_response_model2 = ListDocumentsResponse(**list_documents_response_model_dict) + + # Verify the model instances are equivalent + assert list_documents_response_model == list_documents_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_documents_response_model_json2 = list_documents_response_model.to_dict() + assert list_documents_response_model_json2 == list_documents_response_model_json + class TestModel_ListFieldsResponse(): """ Test Class for ListFieldsResponse @@ -4080,9 +6702,6 @@ def test_list_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. field_model = {} # Field - field_model['field'] = 'testString' - field_model['type'] = 'nested' - field_model['collection_id'] = 'testString' # Construct a json representation of a ListFieldsResponse model list_fields_response_model_json = {} @@ -4115,23 +6734,9 @@ def test_list_projects_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus - project_list_details_relevancy_training_status_model['data_updated'] = 'testString' - project_list_details_relevancy_training_status_model['total_examples'] = 38 - project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True - project_list_details_relevancy_training_status_model['processing'] = True - project_list_details_relevancy_training_status_model['minimum_examples_added'] = True - project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' - project_list_details_relevancy_training_status_model['available'] = True - project_list_details_relevancy_training_status_model['notices'] = 38 - project_list_details_relevancy_training_status_model['minimum_queries_added'] = True - project_list_details_model = {} # ProjectListDetails - project_list_details_model['project_id'] = 'testString' project_list_details_model['name'] = 'testString' project_list_details_model['type'] = 'document_retrieval' - project_list_details_model['relevancy_training_status'] = project_list_details_relevancy_training_status_model - project_list_details_model['collection_count'] = 38 # Construct a json representation of a ListProjectsResponse model list_projects_response_model_json = {} @@ -4152,6 +6757,68 @@ def test_list_projects_response_serialization(self): list_projects_response_model_json2 = list_projects_response_model.to_dict() assert list_projects_response_model_json2 == list_projects_response_model_json +class TestModel_ModelEvaluationMacroAverage(): + """ + Test Class for ModelEvaluationMacroAverage + """ + + def test_model_evaluation_macro_average_serialization(self): + """ + Test serialization/deserialization for ModelEvaluationMacroAverage + """ + + # Construct a json representation of a ModelEvaluationMacroAverage model + model_evaluation_macro_average_model_json = {} + model_evaluation_macro_average_model_json['precision'] = 0 + model_evaluation_macro_average_model_json['recall'] = 0 + model_evaluation_macro_average_model_json['f1'] = 0 + + # Construct a model instance of ModelEvaluationMacroAverage by calling from_dict on the json representation + model_evaluation_macro_average_model = ModelEvaluationMacroAverage.from_dict(model_evaluation_macro_average_model_json) + assert model_evaluation_macro_average_model != False + + # Construct a model instance of ModelEvaluationMacroAverage by calling from_dict on the json representation + model_evaluation_macro_average_model_dict = ModelEvaluationMacroAverage.from_dict(model_evaluation_macro_average_model_json).__dict__ + model_evaluation_macro_average_model2 = ModelEvaluationMacroAverage(**model_evaluation_macro_average_model_dict) + + # Verify the model instances are equivalent + assert model_evaluation_macro_average_model == model_evaluation_macro_average_model2 + + # Convert model instance back to dict and verify no loss of data + model_evaluation_macro_average_model_json2 = model_evaluation_macro_average_model.to_dict() + assert model_evaluation_macro_average_model_json2 == model_evaluation_macro_average_model_json + +class TestModel_ModelEvaluationMicroAverage(): + """ + Test Class for ModelEvaluationMicroAverage + """ + + def test_model_evaluation_micro_average_serialization(self): + """ + Test serialization/deserialization for ModelEvaluationMicroAverage + """ + + # Construct a json representation of a ModelEvaluationMicroAverage model + model_evaluation_micro_average_model_json = {} + model_evaluation_micro_average_model_json['precision'] = 0 + model_evaluation_micro_average_model_json['recall'] = 0 + model_evaluation_micro_average_model_json['f1'] = 0 + + # Construct a model instance of ModelEvaluationMicroAverage by calling from_dict on the json representation + model_evaluation_micro_average_model = ModelEvaluationMicroAverage.from_dict(model_evaluation_micro_average_model_json) + assert model_evaluation_micro_average_model != False + + # Construct a model instance of ModelEvaluationMicroAverage by calling from_dict on the json representation + model_evaluation_micro_average_model_dict = ModelEvaluationMicroAverage.from_dict(model_evaluation_micro_average_model_json).__dict__ + model_evaluation_micro_average_model2 = ModelEvaluationMicroAverage(**model_evaluation_micro_average_model_dict) + + # Verify the model instances are equivalent + assert model_evaluation_micro_average_model == model_evaluation_micro_average_model2 + + # Convert model instance back to dict and verify no loss of data + model_evaluation_micro_average_model_json2 = model_evaluation_micro_average_model.to_dict() + assert model_evaluation_micro_average_model_json2 == model_evaluation_micro_average_model_json + class TestModel_Notice(): """ Test Class for Notice @@ -4164,14 +6831,6 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} - notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = "2019-01-01T12:00:00Z" - notice_model_json['document_id'] = 'testString' - notice_model_json['collection_id'] = 'testString' - notice_model_json['query_id'] = 'testString' - notice_model_json['severity'] = 'warning' - notice_model_json['step'] = 'testString' - notice_model_json['description'] = 'testString' # Construct a model instance of Notice by calling from_dict on the json representation notice_model = Notice.from_dict(notice_model_json) @@ -4188,6 +6847,38 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json +class TestModel_PerClassModelEvaluation(): + """ + Test Class for PerClassModelEvaluation + """ + + def test_per_class_model_evaluation_serialization(self): + """ + Test serialization/deserialization for PerClassModelEvaluation + """ + + # Construct a json representation of a PerClassModelEvaluation model + per_class_model_evaluation_model_json = {} + per_class_model_evaluation_model_json['name'] = 'testString' + per_class_model_evaluation_model_json['precision'] = 0 + per_class_model_evaluation_model_json['recall'] = 0 + per_class_model_evaluation_model_json['f1'] = 0 + + # Construct a model instance of PerClassModelEvaluation by calling from_dict on the json representation + per_class_model_evaluation_model = PerClassModelEvaluation.from_dict(per_class_model_evaluation_model_json) + assert per_class_model_evaluation_model != False + + # Construct a model instance of PerClassModelEvaluation by calling from_dict on the json representation + per_class_model_evaluation_model_dict = PerClassModelEvaluation.from_dict(per_class_model_evaluation_model_json).__dict__ + per_class_model_evaluation_model2 = PerClassModelEvaluation(**per_class_model_evaluation_model_dict) + + # Verify the model instances are equivalent + assert per_class_model_evaluation_model == per_class_model_evaluation_model2 + + # Convert model instance back to dict and verify no loss of data + per_class_model_evaluation_model_json2 = per_class_model_evaluation_model.to_dict() + assert per_class_model_evaluation_model_json2 == per_class_model_evaluation_model_json + class TestModel_ProjectDetails(): """ Test Class for ProjectDetails @@ -4200,17 +6891,6 @@ def test_project_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus - project_list_details_relevancy_training_status_model['data_updated'] = 'testString' - project_list_details_relevancy_training_status_model['total_examples'] = 38 - project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True - project_list_details_relevancy_training_status_model['processing'] = True - project_list_details_relevancy_training_status_model['minimum_examples_added'] = True - project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' - project_list_details_relevancy_training_status_model['available'] = True - project_list_details_relevancy_training_status_model['notices'] = 38 - project_list_details_relevancy_training_status_model['minimum_queries_added'] = True - default_query_params_passages_model = {} # DefaultQueryParamsPassages default_query_params_passages_model['enabled'] = True default_query_params_passages_model['count'] = 38 @@ -4242,11 +6922,8 @@ def test_project_details_serialization(self): # Construct a json representation of a ProjectDetails model project_details_model_json = {} - project_details_model_json['project_id'] = 'testString' project_details_model_json['name'] = 'testString' project_details_model_json['type'] = 'document_retrieval' - project_details_model_json['relevancy_training_status'] = project_list_details_relevancy_training_status_model - project_details_model_json['collection_count'] = 38 project_details_model_json['default_query_parameters'] = default_query_params_model # Construct a model instance of ProjectDetails by calling from_dict on the json representation @@ -4274,26 +6951,10 @@ def test_project_list_details_serialization(self): Test serialization/deserialization for ProjectListDetails """ - # Construct dict forms of any model objects needed in order to build this model. - - project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus - project_list_details_relevancy_training_status_model['data_updated'] = 'testString' - project_list_details_relevancy_training_status_model['total_examples'] = 38 - project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True - project_list_details_relevancy_training_status_model['processing'] = True - project_list_details_relevancy_training_status_model['minimum_examples_added'] = True - project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' - project_list_details_relevancy_training_status_model['available'] = True - project_list_details_relevancy_training_status_model['notices'] = 38 - project_list_details_relevancy_training_status_model['minimum_queries_added'] = True - # Construct a json representation of a ProjectListDetails model project_list_details_model_json = {} - project_list_details_model_json['project_id'] = 'testString' project_list_details_model_json['name'] = 'testString' project_list_details_model_json['type'] = 'document_retrieval' - project_list_details_model_json['relevancy_training_status'] = project_list_details_relevancy_training_status_model - project_list_details_model_json['collection_count'] = 38 # Construct a model instance of ProjectListDetails by calling from_dict on the json representation project_list_details_model = ProjectListDetails.from_dict(project_list_details_model_json) @@ -4347,35 +7008,6 @@ def test_project_list_details_relevancy_training_status_serialization(self): project_list_details_relevancy_training_status_model_json2 = project_list_details_relevancy_training_status_model.to_dict() assert project_list_details_relevancy_training_status_model_json2 == project_list_details_relevancy_training_status_model_json -class TestModel_QueryAggregation(): - """ - Test Class for QueryAggregation - """ - - def test_query_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryAggregation - """ - - # Construct a json representation of a QueryAggregation model - query_aggregation_model_json = {} - query_aggregation_model_json['type'] = 'testString' - - # Construct a model instance of QueryAggregation by calling from_dict on the json representation - query_aggregation_model = QueryAggregation.from_dict(query_aggregation_model_json) - assert query_aggregation_model != False - - # Construct a copy of the model instance by calling from_dict on the output of to_dict - query_aggregation_model_json2 = query_aggregation_model.to_dict() - query_aggregation_model2 = QueryAggregation.from_dict(query_aggregation_model_json2) - - # Verify the model instances are equivalent - assert query_aggregation_model == query_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_aggregation_model_json2 = query_aggregation_model.to_dict() - assert query_aggregation_model_json2 == query_aggregation_model_json - class TestModel_QueryGroupByAggregationResult(): """ Test Class for QueryGroupByAggregationResult @@ -4386,21 +7018,14 @@ def test_query_group_by_aggregation_result_serialization(self): Test serialization/deserialization for QueryGroupByAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryGroupByAggregationResult model query_group_by_aggregation_result_model_json = {} query_group_by_aggregation_result_model_json['key'] = 'testString' query_group_by_aggregation_result_model_json['matching_results'] = 38 query_group_by_aggregation_result_model_json['relevancy'] = 72.5 query_group_by_aggregation_result_model_json['total_matching_documents'] = 38 - query_group_by_aggregation_result_model_json['estimated_matching_documents'] = 38 - query_group_by_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_group_by_aggregation_result_model_json['estimated_matching_results'] = 72.5 + query_group_by_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryGroupByAggregationResult by calling from_dict on the json representation query_group_by_aggregation_result_model = QueryGroupByAggregationResult.from_dict(query_group_by_aggregation_result_model_json) @@ -4427,18 +7052,11 @@ def test_query_histogram_aggregation_result_serialization(self): Test serialization/deserialization for QueryHistogramAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryHistogramAggregationResult model query_histogram_aggregation_result_model_json = {} query_histogram_aggregation_result_model_json['key'] = 26 query_histogram_aggregation_result_model_json['matching_results'] = 38 - query_histogram_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_histogram_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) @@ -4491,6 +7109,37 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json2 = query_large_passages_model.to_dict() assert query_large_passages_model_json2 == query_large_passages_model_json +class TestModel_QueryLargeSimilar(): + """ + Test Class for QueryLargeSimilar + """ + + def test_query_large_similar_serialization(self): + """ + Test serialization/deserialization for QueryLargeSimilar + """ + + # Construct a json representation of a QueryLargeSimilar model + query_large_similar_model_json = {} + query_large_similar_model_json['enabled'] = False + query_large_similar_model_json['document_ids'] = ['testString'] + query_large_similar_model_json['fields'] = ['testString'] + + # Construct a model instance of QueryLargeSimilar by calling from_dict on the json representation + query_large_similar_model = QueryLargeSimilar.from_dict(query_large_similar_model_json) + assert query_large_similar_model != False + + # Construct a model instance of QueryLargeSimilar by calling from_dict on the json representation + query_large_similar_model_dict = QueryLargeSimilar.from_dict(query_large_similar_model_json).__dict__ + query_large_similar_model2 = QueryLargeSimilar(**query_large_similar_model_dict) + + # Verify the model instances are equivalent + assert query_large_similar_model == query_large_similar_model2 + + # Convert model instance back to dict and verify no loss of data + query_large_similar_model_json2 = query_large_similar_model.to_dict() + assert query_large_similar_model_json2 == query_large_similar_model_json + class TestModel_QueryLargeSuggestedRefinements(): """ Test Class for QueryLargeSuggestedRefinements @@ -4564,14 +7213,6 @@ def test_query_notices_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = "2019-01-01T12:00:00Z" - notice_model['document_id'] = 'testString' - notice_model['collection_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' # Construct a json representation of a QueryNoticesResponse model query_notices_response_model_json = {} @@ -4593,6 +7234,35 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json +class TestModel_QueryPairAggregationResult(): + """ + Test Class for QueryPairAggregationResult + """ + + def test_query_pair_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryPairAggregationResult + """ + + # Construct a json representation of a QueryPairAggregationResult model + query_pair_aggregation_result_model_json = {} + query_pair_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + + # Construct a model instance of QueryPairAggregationResult by calling from_dict on the json representation + query_pair_aggregation_result_model = QueryPairAggregationResult.from_dict(query_pair_aggregation_result_model_json) + assert query_pair_aggregation_result_model != False + + # Construct a model instance of QueryPairAggregationResult by calling from_dict on the json representation + query_pair_aggregation_result_model_dict = QueryPairAggregationResult.from_dict(query_pair_aggregation_result_model_json).__dict__ + query_pair_aggregation_result_model2 = QueryPairAggregationResult(**query_pair_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_pair_aggregation_result_model == query_pair_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_pair_aggregation_result_model_json2 = query_pair_aggregation_result_model.to_dict() + assert query_pair_aggregation_result_model_json2 == query_pair_aggregation_result_model_json + class TestModel_QueryResponse(): """ Test Class for QueryResponse @@ -4608,7 +7278,7 @@ def test_query_response_serialization(self): query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' - query_result_metadata_model['confidence'] = 72.5 + query_result_metadata_model['confidence'] = 0 result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' @@ -4621,20 +7291,29 @@ def test_query_response_serialization(self): query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' - query_result_passage_model['confidence'] = 0 query_result_passage_model['answers'] = [result_passage_answer_model] query_result_model = {} # QueryResult query_result_model['document_id'] = 'testString' - query_result_model['metadata'] = {} + query_result_model['metadata'] = {'foo': 'bar'} query_result_model['result_metadata'] = query_result_metadata_model query_result_model['document_passages'] = [query_result_passage_model] - query_result_model['id'] = { 'foo': 'bar' } - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 + query_result_model['id'] = 'watson-generated ID' + + query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model['key'] = 'active' + query_term_aggregation_result_model['matching_results'] = 34 + query_term_aggregation_result_model['relevancy'] = 72.5 + query_term_aggregation_result_model['total_matching_documents'] = 38 + query_term_aggregation_result_model['estimated_matching_results'] = 72.5 + query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + query_aggregation_model = {} # QueryAggregationQueryTermAggregation + query_aggregation_model['type'] = 'term' + query_aggregation_model['field'] = 'field' + query_aggregation_model['count'] = 1 + query_aggregation_model['name'] = 'testString' + query_aggregation_model['results'] = [query_term_aggregation_result_model] retrieval_details_model = {} # RetrievalDetails retrieval_details_model['document_retrieval_strategy'] = 'untrained' @@ -4652,7 +7331,7 @@ def test_query_response_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['location'] = {'foo': 'bar'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -4671,7 +7350,7 @@ def test_query_response_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['location'] = {'foo': 'bar'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -4760,7 +7439,6 @@ def test_query_response_serialization(self): query_response_passage_model['start_offset'] = 38 query_response_passage_model['end_offset'] = 38 query_response_passage_model['field'] = 'testString' - query_response_passage_model['confidence'] = 0 query_response_passage_model['answers'] = [result_passage_answer_model] # Construct a json representation of a QueryResponse model @@ -4816,7 +7494,6 @@ def test_query_response_passage_serialization(self): query_response_passage_model_json['start_offset'] = 38 query_response_passage_model_json['end_offset'] = 38 query_response_passage_model_json['field'] = 'testString' - query_response_passage_model_json['confidence'] = 0 query_response_passage_model_json['answers'] = [result_passage_answer_model] # Construct a model instance of QueryResponsePassage by calling from_dict on the json representation @@ -4849,7 +7526,7 @@ def test_query_result_serialization(self): query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' - query_result_metadata_model['confidence'] = 72.5 + query_result_metadata_model['confidence'] = 0 result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' @@ -4862,16 +7539,15 @@ def test_query_result_serialization(self): query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' - query_result_passage_model['confidence'] = 0 query_result_passage_model['answers'] = [result_passage_answer_model] # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['document_id'] = 'testString' - query_result_model_json['metadata'] = {} + query_result_model_json['metadata'] = {'foo': 'bar'} query_result_model_json['result_metadata'] = query_result_metadata_model query_result_model_json['document_passages'] = [query_result_passage_model] - query_result_model_json['foo'] = { 'foo': 'bar' } + query_result_model_json['foo'] = 'testString' # Construct a model instance of QueryResult by calling from_dict on the json representation query_result_model = QueryResult.from_dict(query_result_model_json) @@ -4893,7 +7569,7 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': 'testString'} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict @@ -4912,7 +7588,7 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json = {} query_result_metadata_model_json['document_retrieval_source'] = 'search' query_result_metadata_model_json['collection_id'] = 'testString' - query_result_metadata_model_json['confidence'] = 72.5 + query_result_metadata_model_json['confidence'] = 0 # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation query_result_metadata_model = QueryResultMetadata.from_dict(query_result_metadata_model_json) @@ -4953,7 +7629,6 @@ def test_query_result_passage_serialization(self): query_result_passage_model_json['start_offset'] = 38 query_result_passage_model_json['end_offset'] = 38 query_result_passage_model_json['field'] = 'testString' - query_result_passage_model_json['confidence'] = 0 query_result_passage_model_json['answers'] = [result_passage_answer_model] # Construct a model instance of QueryResultPassage by calling from_dict on the json representation @@ -5022,7 +7697,7 @@ def test_query_table_result_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['location'] = {'foo': 'bar'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -5041,7 +7716,7 @@ def test_query_table_result_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['location'] = {'foo': 'bar'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -5148,21 +7823,14 @@ def test_query_term_aggregation_result_serialization(self): Test serialization/deserialization for QueryTermAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryTermAggregationResult model query_term_aggregation_result_model_json = {} query_term_aggregation_result_model_json['key'] = 'testString' query_term_aggregation_result_model_json['matching_results'] = 38 query_term_aggregation_result_model_json['relevancy'] = 72.5 query_term_aggregation_result_model_json['total_matching_documents'] = 38 - query_term_aggregation_result_model_json['estimated_matching_documents'] = 38 - query_term_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_term_aggregation_result_model_json['estimated_matching_results'] = 72.5 + query_term_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) @@ -5189,19 +7857,12 @@ def test_query_timeslice_aggregation_result_serialization(self): Test serialization/deserialization for QueryTimesliceAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryTimesliceAggregationResult model query_timeslice_aggregation_result_model_json = {} query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' query_timeslice_aggregation_result_model_json['key'] = 26 query_timeslice_aggregation_result_model_json['matching_results'] = 26 - query_timeslice_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_timeslice_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) @@ -5231,7 +7892,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{}] + query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -5248,6 +7909,64 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json +class TestModel_QueryTopicAggregationResult(): + """ + Test Class for QueryTopicAggregationResult + """ + + def test_query_topic_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTopicAggregationResult + """ + + # Construct a json representation of a QueryTopicAggregationResult model + query_topic_aggregation_result_model_json = {} + query_topic_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + + # Construct a model instance of QueryTopicAggregationResult by calling from_dict on the json representation + query_topic_aggregation_result_model = QueryTopicAggregationResult.from_dict(query_topic_aggregation_result_model_json) + assert query_topic_aggregation_result_model != False + + # Construct a model instance of QueryTopicAggregationResult by calling from_dict on the json representation + query_topic_aggregation_result_model_dict = QueryTopicAggregationResult.from_dict(query_topic_aggregation_result_model_json).__dict__ + query_topic_aggregation_result_model2 = QueryTopicAggregationResult(**query_topic_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_topic_aggregation_result_model == query_topic_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_topic_aggregation_result_model_json2 = query_topic_aggregation_result_model.to_dict() + assert query_topic_aggregation_result_model_json2 == query_topic_aggregation_result_model_json + +class TestModel_QueryTrendAggregationResult(): + """ + Test Class for QueryTrendAggregationResult + """ + + def test_query_trend_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTrendAggregationResult + """ + + # Construct a json representation of a QueryTrendAggregationResult model + query_trend_aggregation_result_model_json = {} + query_trend_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + + # Construct a model instance of QueryTrendAggregationResult by calling from_dict on the json representation + query_trend_aggregation_result_model = QueryTrendAggregationResult.from_dict(query_trend_aggregation_result_model_json) + assert query_trend_aggregation_result_model != False + + # Construct a model instance of QueryTrendAggregationResult by calling from_dict on the json representation + query_trend_aggregation_result_model_dict = QueryTrendAggregationResult.from_dict(query_trend_aggregation_result_model_json).__dict__ + query_trend_aggregation_result_model2 = QueryTrendAggregationResult(**query_trend_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_trend_aggregation_result_model == query_trend_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_trend_aggregation_result_model_json2 = query_trend_aggregation_result_model.to_dict() + assert query_trend_aggregation_result_model_json2 == query_trend_aggregation_result_model_json + class TestModel_ResultPassageAnswer(): """ Test Class for ResultPassageAnswer @@ -5309,6 +8028,35 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json +class TestModel_StopWordList(): + """ + Test Class for StopWordList + """ + + def test_stop_word_list_serialization(self): + """ + Test serialization/deserialization for StopWordList + """ + + # Construct a json representation of a StopWordList model + stop_word_list_model_json = {} + stop_word_list_model_json['stopwords'] = ['testString'] + + # Construct a model instance of StopWordList by calling from_dict on the json representation + stop_word_list_model = StopWordList.from_dict(stop_word_list_model_json) + assert stop_word_list_model != False + + # Construct a model instance of StopWordList by calling from_dict on the json representation + stop_word_list_model_dict = StopWordList.from_dict(stop_word_list_model_json).__dict__ + stop_word_list_model2 = StopWordList(**stop_word_list_model_dict) + + # Verify the model instances are equivalent + assert stop_word_list_model == stop_word_list_model2 + + # Convert model instance back to dict and verify no loss of data + stop_word_list_model_json2 = stop_word_list_model.to_dict() + assert stop_word_list_model_json2 == stop_word_list_model_json + class TestModel_TableBodyCells(): """ Test Class for TableBodyCells @@ -5554,7 +8302,7 @@ def test_table_column_headers_serialization(self): # Construct a json representation of a TableColumnHeaders model table_column_headers_model_json = {} table_column_headers_model_json['cell_id'] = 'testString' - table_column_headers_model_json['location'] = { 'foo': 'bar' } + table_column_headers_model_json['location'] = {'foo': 'bar'} table_column_headers_model_json['text'] = 'testString' table_column_headers_model_json['text_normalized'] = 'testString' table_column_headers_model_json['row_index_begin'] = 26 @@ -5620,7 +8368,7 @@ def test_table_headers_serialization(self): # Construct a json representation of a TableHeaders model table_headers_model_json = {} table_headers_model_json['cell_id'] = 'testString' - table_headers_model_json['location'] = { 'foo': 'bar' } + table_headers_model_json['location'] = {'foo': 'bar'} table_headers_model_json['text'] = 'testString' table_headers_model_json['row_index_begin'] = 26 table_headers_model_json['row_index_end'] = 26 @@ -5710,7 +8458,7 @@ def test_table_result_table_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['location'] = {'foo': 'bar'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -5729,7 +8477,7 @@ def test_table_result_table_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['location'] = {'foo': 'bar'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -5998,8 +8746,6 @@ def test_training_example_serialization(self): training_example_model_json['document_id'] = 'testString' training_example_model_json['collection_id'] = 'testString' training_example_model_json['relevance'] = 38 - training_example_model_json['created'] = "2019-01-01T12:00:00Z" - training_example_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of TrainingExample by calling from_dict on the json representation training_example_model = TrainingExample.from_dict(training_example_model_json) @@ -6032,16 +8778,11 @@ def test_training_query_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = "2019-01-01T12:00:00Z" - training_example_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a TrainingQuery model training_query_model_json = {} - training_query_model_json['query_id'] = 'testString' training_query_model_json['natural_language_query'] = 'testString' training_query_model_json['filter'] = 'testString' - training_query_model_json['created'] = "2019-01-01T12:00:00Z" - training_query_model_json['updated'] = "2019-01-01T12:00:00Z" training_query_model_json['examples'] = [training_example_model] # Construct a model instance of TrainingQuery by calling from_dict on the json representation @@ -6075,15 +8816,10 @@ def test_training_query_set_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = "2019-01-01T12:00:00Z" - training_example_model['updated'] = "2019-01-01T12:00:00Z" training_query_model = {} # TrainingQuery - training_query_model['query_id'] = 'testString' training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' - training_query_model['created'] = "2019-01-01T12:00:00Z" - training_query_model['updated'] = "2019-01-01T12:00:00Z" training_query_model['examples'] = [training_example_model] # Construct a json representation of a TrainingQuerySet model @@ -6105,261 +8841,449 @@ def test_training_query_set_serialization(self): training_query_set_model_json2 = training_query_set_model.to_dict() assert training_query_set_model_json2 == training_query_set_model_json -class TestModel_QueryCalculationAggregation(): +class TestModel_UpdateDocumentClassifier(): + """ + Test Class for UpdateDocumentClassifier + """ + + def test_update_document_classifier_serialization(self): + """ + Test serialization/deserialization for UpdateDocumentClassifier + """ + + # Construct a json representation of a UpdateDocumentClassifier model + update_document_classifier_model_json = {} + update_document_classifier_model_json['name'] = 'testString' + update_document_classifier_model_json['description'] = 'testString' + + # Construct a model instance of UpdateDocumentClassifier by calling from_dict on the json representation + update_document_classifier_model = UpdateDocumentClassifier.from_dict(update_document_classifier_model_json) + assert update_document_classifier_model != False + + # Construct a model instance of UpdateDocumentClassifier by calling from_dict on the json representation + update_document_classifier_model_dict = UpdateDocumentClassifier.from_dict(update_document_classifier_model_json).__dict__ + update_document_classifier_model2 = UpdateDocumentClassifier(**update_document_classifier_model_dict) + + # Verify the model instances are equivalent + assert update_document_classifier_model == update_document_classifier_model2 + + # Convert model instance back to dict and verify no loss of data + update_document_classifier_model_json2 = update_document_classifier_model.to_dict() + assert update_document_classifier_model_json2 == update_document_classifier_model_json + +class TestModel_QueryAggregationQueryCalculationAggregation(): """ - Test Class for QueryCalculationAggregation + Test Class for QueryAggregationQueryCalculationAggregation """ - def test_query_calculation_aggregation_serialization(self): + def test_query_aggregation_query_calculation_aggregation_serialization(self): """ - Test serialization/deserialization for QueryCalculationAggregation + Test serialization/deserialization for QueryAggregationQueryCalculationAggregation """ - # Construct a json representation of a QueryCalculationAggregation model - query_calculation_aggregation_model_json = {} - query_calculation_aggregation_model_json['type'] = 'unique_count' - query_calculation_aggregation_model_json['field'] = 'testString' - query_calculation_aggregation_model_json['value'] = 72.5 + # Construct a json representation of a QueryAggregationQueryCalculationAggregation model + query_aggregation_query_calculation_aggregation_model_json = {} + query_aggregation_query_calculation_aggregation_model_json['type'] = 'unique_count' + query_aggregation_query_calculation_aggregation_model_json['field'] = 'testString' + query_aggregation_query_calculation_aggregation_model_json['value'] = 72.5 - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json) - assert query_calculation_aggregation_model != False + # Construct a model instance of QueryAggregationQueryCalculationAggregation by calling from_dict on the json representation + query_aggregation_query_calculation_aggregation_model = QueryAggregationQueryCalculationAggregation.from_dict(query_aggregation_query_calculation_aggregation_model_json) + assert query_aggregation_query_calculation_aggregation_model != False - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model_dict = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json).__dict__ - query_calculation_aggregation_model2 = QueryCalculationAggregation(**query_calculation_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryCalculationAggregation by calling from_dict on the json representation + query_aggregation_query_calculation_aggregation_model_dict = QueryAggregationQueryCalculationAggregation.from_dict(query_aggregation_query_calculation_aggregation_model_json).__dict__ + query_aggregation_query_calculation_aggregation_model2 = QueryAggregationQueryCalculationAggregation(**query_aggregation_query_calculation_aggregation_model_dict) # Verify the model instances are equivalent - assert query_calculation_aggregation_model == query_calculation_aggregation_model2 + assert query_aggregation_query_calculation_aggregation_model == query_aggregation_query_calculation_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() - assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json + query_aggregation_query_calculation_aggregation_model_json2 = query_aggregation_query_calculation_aggregation_model.to_dict() + assert query_aggregation_query_calculation_aggregation_model_json2 == query_aggregation_query_calculation_aggregation_model_json -class TestModel_QueryFilterAggregation(): +class TestModel_QueryAggregationQueryFilterAggregation(): """ - Test Class for QueryFilterAggregation + Test Class for QueryAggregationQueryFilterAggregation """ - def test_query_filter_aggregation_serialization(self): + def test_query_aggregation_query_filter_aggregation_serialization(self): """ - Test serialization/deserialization for QueryFilterAggregation + Test serialization/deserialization for QueryAggregationQueryFilterAggregation """ - # Construct a json representation of a QueryFilterAggregation model - query_filter_aggregation_model_json = {} - query_filter_aggregation_model_json['type'] = 'filter' - query_filter_aggregation_model_json['match'] = 'testString' - query_filter_aggregation_model_json['matching_results'] = 26 + # Construct a json representation of a QueryAggregationQueryFilterAggregation model + query_aggregation_query_filter_aggregation_model_json = {} + query_aggregation_query_filter_aggregation_model_json['type'] = 'filter' + query_aggregation_query_filter_aggregation_model_json['match'] = 'testString' + query_aggregation_query_filter_aggregation_model_json['matching_results'] = 26 + query_aggregation_query_filter_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json) - assert query_filter_aggregation_model != False + # Construct a model instance of QueryAggregationQueryFilterAggregation by calling from_dict on the json representation + query_aggregation_query_filter_aggregation_model = QueryAggregationQueryFilterAggregation.from_dict(query_aggregation_query_filter_aggregation_model_json) + assert query_aggregation_query_filter_aggregation_model != False - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model_dict = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json).__dict__ - query_filter_aggregation_model2 = QueryFilterAggregation(**query_filter_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryFilterAggregation by calling from_dict on the json representation + query_aggregation_query_filter_aggregation_model_dict = QueryAggregationQueryFilterAggregation.from_dict(query_aggregation_query_filter_aggregation_model_json).__dict__ + query_aggregation_query_filter_aggregation_model2 = QueryAggregationQueryFilterAggregation(**query_aggregation_query_filter_aggregation_model_dict) # Verify the model instances are equivalent - assert query_filter_aggregation_model == query_filter_aggregation_model2 + assert query_aggregation_query_filter_aggregation_model == query_aggregation_query_filter_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() - assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json + query_aggregation_query_filter_aggregation_model_json2 = query_aggregation_query_filter_aggregation_model.to_dict() + assert query_aggregation_query_filter_aggregation_model_json2 == query_aggregation_query_filter_aggregation_model_json -class TestModel_QueryGroupByAggregation(): +class TestModel_QueryAggregationQueryGroupByAggregation(): """ - Test Class for QueryGroupByAggregation + Test Class for QueryAggregationQueryGroupByAggregation """ - def test_query_group_by_aggregation_serialization(self): + def test_query_aggregation_query_group_by_aggregation_serialization(self): """ - Test serialization/deserialization for QueryGroupByAggregation + Test serialization/deserialization for QueryAggregationQueryGroupByAggregation """ - # Construct a json representation of a QueryGroupByAggregation model - query_group_by_aggregation_model_json = {} - query_group_by_aggregation_model_json['type'] = 'group_by' + # Construct dict forms of any model objects needed in order to build this model. + + query_group_by_aggregation_result_model = {} # QueryGroupByAggregationResult + query_group_by_aggregation_result_model['key'] = 'testString' + query_group_by_aggregation_result_model['matching_results'] = 38 + query_group_by_aggregation_result_model['relevancy'] = 72.5 + query_group_by_aggregation_result_model['total_matching_documents'] = 38 + query_group_by_aggregation_result_model['estimated_matching_results'] = 72.5 + query_group_by_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryGroupByAggregation model + query_aggregation_query_group_by_aggregation_model_json = {} + query_aggregation_query_group_by_aggregation_model_json['type'] = 'group_by' + query_aggregation_query_group_by_aggregation_model_json['results'] = [query_group_by_aggregation_result_model] - # Construct a model instance of QueryGroupByAggregation by calling from_dict on the json representation - query_group_by_aggregation_model = QueryGroupByAggregation.from_dict(query_group_by_aggregation_model_json) - assert query_group_by_aggregation_model != False + # Construct a model instance of QueryAggregationQueryGroupByAggregation by calling from_dict on the json representation + query_aggregation_query_group_by_aggregation_model = QueryAggregationQueryGroupByAggregation.from_dict(query_aggregation_query_group_by_aggregation_model_json) + assert query_aggregation_query_group_by_aggregation_model != False - # Construct a model instance of QueryGroupByAggregation by calling from_dict on the json representation - query_group_by_aggregation_model_dict = QueryGroupByAggregation.from_dict(query_group_by_aggregation_model_json).__dict__ - query_group_by_aggregation_model2 = QueryGroupByAggregation(**query_group_by_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryGroupByAggregation by calling from_dict on the json representation + query_aggregation_query_group_by_aggregation_model_dict = QueryAggregationQueryGroupByAggregation.from_dict(query_aggregation_query_group_by_aggregation_model_json).__dict__ + query_aggregation_query_group_by_aggregation_model2 = QueryAggregationQueryGroupByAggregation(**query_aggregation_query_group_by_aggregation_model_dict) # Verify the model instances are equivalent - assert query_group_by_aggregation_model == query_group_by_aggregation_model2 + assert query_aggregation_query_group_by_aggregation_model == query_aggregation_query_group_by_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_group_by_aggregation_model_json2 = query_group_by_aggregation_model.to_dict() - assert query_group_by_aggregation_model_json2 == query_group_by_aggregation_model_json + query_aggregation_query_group_by_aggregation_model_json2 = query_aggregation_query_group_by_aggregation_model.to_dict() + assert query_aggregation_query_group_by_aggregation_model_json2 == query_aggregation_query_group_by_aggregation_model_json -class TestModel_QueryHistogramAggregation(): +class TestModel_QueryAggregationQueryHistogramAggregation(): """ - Test Class for QueryHistogramAggregation + Test Class for QueryAggregationQueryHistogramAggregation """ - def test_query_histogram_aggregation_serialization(self): + def test_query_aggregation_query_histogram_aggregation_serialization(self): """ - Test serialization/deserialization for QueryHistogramAggregation + Test serialization/deserialization for QueryAggregationQueryHistogramAggregation """ - # Construct a json representation of a QueryHistogramAggregation model - query_histogram_aggregation_model_json = {} - query_histogram_aggregation_model_json['type'] = 'histogram' - query_histogram_aggregation_model_json['field'] = 'testString' - query_histogram_aggregation_model_json['interval'] = 38 - query_histogram_aggregation_model_json['name'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. + + query_histogram_aggregation_result_model = {} # QueryHistogramAggregationResult + query_histogram_aggregation_result_model['key'] = 26 + query_histogram_aggregation_result_model['matching_results'] = 38 + query_histogram_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json) - assert query_histogram_aggregation_model != False + # Construct a json representation of a QueryAggregationQueryHistogramAggregation model + query_aggregation_query_histogram_aggregation_model_json = {} + query_aggregation_query_histogram_aggregation_model_json['type'] = 'histogram' + query_aggregation_query_histogram_aggregation_model_json['field'] = 'testString' + query_aggregation_query_histogram_aggregation_model_json['interval'] = 38 + query_aggregation_query_histogram_aggregation_model_json['name'] = 'testString' + query_aggregation_query_histogram_aggregation_model_json['results'] = [query_histogram_aggregation_result_model] - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model_dict = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json).__dict__ - query_histogram_aggregation_model2 = QueryHistogramAggregation(**query_histogram_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryHistogramAggregation by calling from_dict on the json representation + query_aggregation_query_histogram_aggregation_model = QueryAggregationQueryHistogramAggregation.from_dict(query_aggregation_query_histogram_aggregation_model_json) + assert query_aggregation_query_histogram_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryHistogramAggregation by calling from_dict on the json representation + query_aggregation_query_histogram_aggregation_model_dict = QueryAggregationQueryHistogramAggregation.from_dict(query_aggregation_query_histogram_aggregation_model_json).__dict__ + query_aggregation_query_histogram_aggregation_model2 = QueryAggregationQueryHistogramAggregation(**query_aggregation_query_histogram_aggregation_model_dict) # Verify the model instances are equivalent - assert query_histogram_aggregation_model == query_histogram_aggregation_model2 + assert query_aggregation_query_histogram_aggregation_model == query_aggregation_query_histogram_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() - assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json + query_aggregation_query_histogram_aggregation_model_json2 = query_aggregation_query_histogram_aggregation_model.to_dict() + assert query_aggregation_query_histogram_aggregation_model_json2 == query_aggregation_query_histogram_aggregation_model_json -class TestModel_QueryNestedAggregation(): +class TestModel_QueryAggregationQueryNestedAggregation(): """ - Test Class for QueryNestedAggregation + Test Class for QueryAggregationQueryNestedAggregation """ - def test_query_nested_aggregation_serialization(self): + def test_query_aggregation_query_nested_aggregation_serialization(self): """ - Test serialization/deserialization for QueryNestedAggregation + Test serialization/deserialization for QueryAggregationQueryNestedAggregation """ - # Construct a json representation of a QueryNestedAggregation model - query_nested_aggregation_model_json = {} - query_nested_aggregation_model_json['type'] = 'nested' - query_nested_aggregation_model_json['path'] = 'testString' - query_nested_aggregation_model_json['matching_results'] = 26 + # Construct a json representation of a QueryAggregationQueryNestedAggregation model + query_aggregation_query_nested_aggregation_model_json = {} + query_aggregation_query_nested_aggregation_model_json['type'] = 'nested' + query_aggregation_query_nested_aggregation_model_json['path'] = 'testString' + query_aggregation_query_nested_aggregation_model_json['matching_results'] = 26 + query_aggregation_query_nested_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json) - assert query_nested_aggregation_model != False + # Construct a model instance of QueryAggregationQueryNestedAggregation by calling from_dict on the json representation + query_aggregation_query_nested_aggregation_model = QueryAggregationQueryNestedAggregation.from_dict(query_aggregation_query_nested_aggregation_model_json) + assert query_aggregation_query_nested_aggregation_model != False - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model_dict = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json).__dict__ - query_nested_aggregation_model2 = QueryNestedAggregation(**query_nested_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryNestedAggregation by calling from_dict on the json representation + query_aggregation_query_nested_aggregation_model_dict = QueryAggregationQueryNestedAggregation.from_dict(query_aggregation_query_nested_aggregation_model_json).__dict__ + query_aggregation_query_nested_aggregation_model2 = QueryAggregationQueryNestedAggregation(**query_aggregation_query_nested_aggregation_model_dict) # Verify the model instances are equivalent - assert query_nested_aggregation_model == query_nested_aggregation_model2 + assert query_aggregation_query_nested_aggregation_model == query_aggregation_query_nested_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() - assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json + query_aggregation_query_nested_aggregation_model_json2 = query_aggregation_query_nested_aggregation_model.to_dict() + assert query_aggregation_query_nested_aggregation_model_json2 == query_aggregation_query_nested_aggregation_model_json -class TestModel_QueryTermAggregation(): +class TestModel_QueryAggregationQueryPairAggregation(): """ - Test Class for QueryTermAggregation + Test Class for QueryAggregationQueryPairAggregation """ - def test_query_term_aggregation_serialization(self): + def test_query_aggregation_query_pair_aggregation_serialization(self): """ - Test serialization/deserialization for QueryTermAggregation + Test serialization/deserialization for QueryAggregationQueryPairAggregation """ - # Construct a json representation of a QueryTermAggregation model - query_term_aggregation_model_json = {} - query_term_aggregation_model_json['type'] = 'term' - query_term_aggregation_model_json['field'] = 'testString' - query_term_aggregation_model_json['count'] = 38 - query_term_aggregation_model_json['name'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. + + query_pair_aggregation_result_model = {} # QueryPairAggregationResult + query_pair_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryPairAggregation model + query_aggregation_query_pair_aggregation_model_json = {} + query_aggregation_query_pair_aggregation_model_json['type'] = 'pair' + query_aggregation_query_pair_aggregation_model_json['first'] = 'testString' + query_aggregation_query_pair_aggregation_model_json['second'] = 'testString' + query_aggregation_query_pair_aggregation_model_json['show_estimated_matching_results'] = False + query_aggregation_query_pair_aggregation_model_json['show_total_matching_documents'] = False + query_aggregation_query_pair_aggregation_model_json['results'] = [query_pair_aggregation_result_model] - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model = QueryTermAggregation.from_dict(query_term_aggregation_model_json) - assert query_term_aggregation_model != False + # Construct a model instance of QueryAggregationQueryPairAggregation by calling from_dict on the json representation + query_aggregation_query_pair_aggregation_model = QueryAggregationQueryPairAggregation.from_dict(query_aggregation_query_pair_aggregation_model_json) + assert query_aggregation_query_pair_aggregation_model != False - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model_dict = QueryTermAggregation.from_dict(query_term_aggregation_model_json).__dict__ - query_term_aggregation_model2 = QueryTermAggregation(**query_term_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryPairAggregation by calling from_dict on the json representation + query_aggregation_query_pair_aggregation_model_dict = QueryAggregationQueryPairAggregation.from_dict(query_aggregation_query_pair_aggregation_model_json).__dict__ + query_aggregation_query_pair_aggregation_model2 = QueryAggregationQueryPairAggregation(**query_aggregation_query_pair_aggregation_model_dict) # Verify the model instances are equivalent - assert query_term_aggregation_model == query_term_aggregation_model2 + assert query_aggregation_query_pair_aggregation_model == query_aggregation_query_pair_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() - assert query_term_aggregation_model_json2 == query_term_aggregation_model_json + query_aggregation_query_pair_aggregation_model_json2 = query_aggregation_query_pair_aggregation_model.to_dict() + assert query_aggregation_query_pair_aggregation_model_json2 == query_aggregation_query_pair_aggregation_model_json -class TestModel_QueryTimesliceAggregation(): +class TestModel_QueryAggregationQueryTermAggregation(): """ - Test Class for QueryTimesliceAggregation + Test Class for QueryAggregationQueryTermAggregation """ - def test_query_timeslice_aggregation_serialization(self): + def test_query_aggregation_query_term_aggregation_serialization(self): """ - Test serialization/deserialization for QueryTimesliceAggregation + Test serialization/deserialization for QueryAggregationQueryTermAggregation """ - # Construct a json representation of a QueryTimesliceAggregation model - query_timeslice_aggregation_model_json = {} - query_timeslice_aggregation_model_json['type'] = 'timeslice' - query_timeslice_aggregation_model_json['field'] = 'testString' - query_timeslice_aggregation_model_json['interval'] = 'testString' - query_timeslice_aggregation_model_json['name'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. + + query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model['key'] = 'testString' + query_term_aggregation_result_model['matching_results'] = 38 + query_term_aggregation_result_model['relevancy'] = 72.5 + query_term_aggregation_result_model['total_matching_documents'] = 38 + query_term_aggregation_result_model['estimated_matching_results'] = 72.5 + query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryTermAggregation model + query_aggregation_query_term_aggregation_model_json = {} + query_aggregation_query_term_aggregation_model_json['type'] = 'term' + query_aggregation_query_term_aggregation_model_json['field'] = 'testString' + query_aggregation_query_term_aggregation_model_json['count'] = 38 + query_aggregation_query_term_aggregation_model_json['name'] = 'testString' + query_aggregation_query_term_aggregation_model_json['results'] = [query_term_aggregation_result_model] + + # Construct a model instance of QueryAggregationQueryTermAggregation by calling from_dict on the json representation + query_aggregation_query_term_aggregation_model = QueryAggregationQueryTermAggregation.from_dict(query_aggregation_query_term_aggregation_model_json) + assert query_aggregation_query_term_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryTermAggregation by calling from_dict on the json representation + query_aggregation_query_term_aggregation_model_dict = QueryAggregationQueryTermAggregation.from_dict(query_aggregation_query_term_aggregation_model_json).__dict__ + query_aggregation_query_term_aggregation_model2 = QueryAggregationQueryTermAggregation(**query_aggregation_query_term_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_aggregation_query_term_aggregation_model == query_aggregation_query_term_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_query_term_aggregation_model_json2 = query_aggregation_query_term_aggregation_model.to_dict() + assert query_aggregation_query_term_aggregation_model_json2 == query_aggregation_query_term_aggregation_model_json + +class TestModel_QueryAggregationQueryTimesliceAggregation(): + """ + Test Class for QueryAggregationQueryTimesliceAggregation + """ + + def test_query_aggregation_query_timeslice_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregationQueryTimesliceAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_timeslice_aggregation_result_model = {} # QueryTimesliceAggregationResult + query_timeslice_aggregation_result_model['key_as_string'] = 'testString' + query_timeslice_aggregation_result_model['key'] = 26 + query_timeslice_aggregation_result_model['matching_results'] = 26 + query_timeslice_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryTimesliceAggregation model + query_aggregation_query_timeslice_aggregation_model_json = {} + query_aggregation_query_timeslice_aggregation_model_json['type'] = 'timeslice' + query_aggregation_query_timeslice_aggregation_model_json['field'] = 'testString' + query_aggregation_query_timeslice_aggregation_model_json['interval'] = 'testString' + query_aggregation_query_timeslice_aggregation_model_json['name'] = 'testString' + query_aggregation_query_timeslice_aggregation_model_json['results'] = [query_timeslice_aggregation_result_model] - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json) - assert query_timeslice_aggregation_model != False + # Construct a model instance of QueryAggregationQueryTimesliceAggregation by calling from_dict on the json representation + query_aggregation_query_timeslice_aggregation_model = QueryAggregationQueryTimesliceAggregation.from_dict(query_aggregation_query_timeslice_aggregation_model_json) + assert query_aggregation_query_timeslice_aggregation_model != False - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model_dict = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json).__dict__ - query_timeslice_aggregation_model2 = QueryTimesliceAggregation(**query_timeslice_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryTimesliceAggregation by calling from_dict on the json representation + query_aggregation_query_timeslice_aggregation_model_dict = QueryAggregationQueryTimesliceAggregation.from_dict(query_aggregation_query_timeslice_aggregation_model_json).__dict__ + query_aggregation_query_timeslice_aggregation_model2 = QueryAggregationQueryTimesliceAggregation(**query_aggregation_query_timeslice_aggregation_model_dict) # Verify the model instances are equivalent - assert query_timeslice_aggregation_model == query_timeslice_aggregation_model2 + assert query_aggregation_query_timeslice_aggregation_model == query_aggregation_query_timeslice_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() - assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json + query_aggregation_query_timeslice_aggregation_model_json2 = query_aggregation_query_timeslice_aggregation_model.to_dict() + assert query_aggregation_query_timeslice_aggregation_model_json2 == query_aggregation_query_timeslice_aggregation_model_json -class TestModel_QueryTopHitsAggregation(): +class TestModel_QueryAggregationQueryTopHitsAggregation(): """ - Test Class for QueryTopHitsAggregation + Test Class for QueryAggregationQueryTopHitsAggregation """ - def test_query_top_hits_aggregation_serialization(self): + def test_query_aggregation_query_top_hits_aggregation_serialization(self): """ - Test serialization/deserialization for QueryTopHitsAggregation + Test serialization/deserialization for QueryAggregationQueryTopHitsAggregation """ # Construct dict forms of any model objects needed in order to build this model. query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{}] + query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryTopHitsAggregation model + query_aggregation_query_top_hits_aggregation_model_json = {} + query_aggregation_query_top_hits_aggregation_model_json['type'] = 'top_hits' + query_aggregation_query_top_hits_aggregation_model_json['size'] = 38 + query_aggregation_query_top_hits_aggregation_model_json['name'] = 'testString' + query_aggregation_query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model + + # Construct a model instance of QueryAggregationQueryTopHitsAggregation by calling from_dict on the json representation + query_aggregation_query_top_hits_aggregation_model = QueryAggregationQueryTopHitsAggregation.from_dict(query_aggregation_query_top_hits_aggregation_model_json) + assert query_aggregation_query_top_hits_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryTopHitsAggregation by calling from_dict on the json representation + query_aggregation_query_top_hits_aggregation_model_dict = QueryAggregationQueryTopHitsAggregation.from_dict(query_aggregation_query_top_hits_aggregation_model_json).__dict__ + query_aggregation_query_top_hits_aggregation_model2 = QueryAggregationQueryTopHitsAggregation(**query_aggregation_query_top_hits_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_aggregation_query_top_hits_aggregation_model == query_aggregation_query_top_hits_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_query_top_hits_aggregation_model_json2 = query_aggregation_query_top_hits_aggregation_model.to_dict() + assert query_aggregation_query_top_hits_aggregation_model_json2 == query_aggregation_query_top_hits_aggregation_model_json + +class TestModel_QueryAggregationQueryTopicAggregation(): + """ + Test Class for QueryAggregationQueryTopicAggregation + """ + + def test_query_aggregation_query_topic_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregationQueryTopicAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_topic_aggregation_result_model = {} # QueryTopicAggregationResult + query_topic_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryTopicAggregation model + query_aggregation_query_topic_aggregation_model_json = {} + query_aggregation_query_topic_aggregation_model_json['type'] = 'topic' + query_aggregation_query_topic_aggregation_model_json['facet'] = 'testString' + query_aggregation_query_topic_aggregation_model_json['time_segments'] = 'testString' + query_aggregation_query_topic_aggregation_model_json['show_estimated_matching_results'] = False + query_aggregation_query_topic_aggregation_model_json['show_total_matching_documents'] = False + query_aggregation_query_topic_aggregation_model_json['results'] = [query_topic_aggregation_result_model] + + # Construct a model instance of QueryAggregationQueryTopicAggregation by calling from_dict on the json representation + query_aggregation_query_topic_aggregation_model = QueryAggregationQueryTopicAggregation.from_dict(query_aggregation_query_topic_aggregation_model_json) + assert query_aggregation_query_topic_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryTopicAggregation by calling from_dict on the json representation + query_aggregation_query_topic_aggregation_model_dict = QueryAggregationQueryTopicAggregation.from_dict(query_aggregation_query_topic_aggregation_model_json).__dict__ + query_aggregation_query_topic_aggregation_model2 = QueryAggregationQueryTopicAggregation(**query_aggregation_query_topic_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_aggregation_query_topic_aggregation_model == query_aggregation_query_topic_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_query_topic_aggregation_model_json2 = query_aggregation_query_topic_aggregation_model.to_dict() + assert query_aggregation_query_topic_aggregation_model_json2 == query_aggregation_query_topic_aggregation_model_json + +class TestModel_QueryAggregationQueryTrendAggregation(): + """ + Test Class for QueryAggregationQueryTrendAggregation + """ + + def test_query_aggregation_query_trend_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregationQueryTrendAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_trend_aggregation_result_model = {} # QueryTrendAggregationResult + query_trend_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] - # Construct a json representation of a QueryTopHitsAggregation model - query_top_hits_aggregation_model_json = {} - query_top_hits_aggregation_model_json['type'] = 'top_hits' - query_top_hits_aggregation_model_json['size'] = 38 - query_top_hits_aggregation_model_json['name'] = 'testString' - query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model + # Construct a json representation of a QueryAggregationQueryTrendAggregation model + query_aggregation_query_trend_aggregation_model_json = {} + query_aggregation_query_trend_aggregation_model_json['type'] = 'trend' + query_aggregation_query_trend_aggregation_model_json['facet'] = 'testString' + query_aggregation_query_trend_aggregation_model_json['time_segments'] = 'testString' + query_aggregation_query_trend_aggregation_model_json['show_estimated_matching_results'] = False + query_aggregation_query_trend_aggregation_model_json['show_total_matching_documents'] = False + query_aggregation_query_trend_aggregation_model_json['results'] = [query_trend_aggregation_result_model] - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json) - assert query_top_hits_aggregation_model != False + # Construct a model instance of QueryAggregationQueryTrendAggregation by calling from_dict on the json representation + query_aggregation_query_trend_aggregation_model = QueryAggregationQueryTrendAggregation.from_dict(query_aggregation_query_trend_aggregation_model_json) + assert query_aggregation_query_trend_aggregation_model != False - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model_dict = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json).__dict__ - query_top_hits_aggregation_model2 = QueryTopHitsAggregation(**query_top_hits_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryTrendAggregation by calling from_dict on the json representation + query_aggregation_query_trend_aggregation_model_dict = QueryAggregationQueryTrendAggregation.from_dict(query_aggregation_query_trend_aggregation_model_json).__dict__ + query_aggregation_query_trend_aggregation_model2 = QueryAggregationQueryTrendAggregation(**query_aggregation_query_trend_aggregation_model_dict) # Verify the model instances are equivalent - assert query_top_hits_aggregation_model == query_top_hits_aggregation_model2 + assert query_aggregation_query_trend_aggregation_model == query_aggregation_query_trend_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_top_hits_aggregation_model_json2 = query_top_hits_aggregation_model.to_dict() - assert query_top_hits_aggregation_model_json2 == query_top_hits_aggregation_model_json + query_aggregation_query_trend_aggregation_model_json2 = query_aggregation_query_trend_aggregation_model.to_dict() + assert query_aggregation_query_trend_aggregation_model_json2 == query_aggregation_query_trend_aggregation_model_json # endregion diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index f0ed3cb4d..fdb19dd00 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2018, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ _service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' @@ -131,7 +131,6 @@ def test_list_languages_value_error(self): with pytest.raises(ValueError): _service.list_languages(**req_copy) - def test_list_languages_value_error_with_retries(self): # Enable retries and run test_list_languages_value_error. _service.enable_retries() @@ -233,7 +232,6 @@ def test_translate_value_error(self): with pytest.raises(ValueError): _service.translate(**req_copy) - def test_translate_value_error_with_retries(self): # Enable retries and run test_translate_value_error. _service.enable_retries() @@ -311,7 +309,6 @@ def test_list_identifiable_languages_value_error(self): with pytest.raises(ValueError): _service.list_identifiable_languages(**req_copy) - def test_list_identifiable_languages_value_error_with_retries(self): # Enable retries and run test_list_identifiable_languages_value_error. _service.enable_retries() @@ -390,7 +387,6 @@ def test_identify_value_error(self): with pytest.raises(ValueError): _service.identify(**req_copy) - def test_identify_value_error_with_retries(self): # Enable retries and run test_identify_value_error. _service.enable_retries() @@ -514,7 +510,6 @@ def test_list_models_value_error(self): with pytest.raises(ValueError): _service.list_models(**req_copy) - def test_list_models_value_error_with_retries(self): # Enable retries and run test_list_models_value_error. _service.enable_retries() @@ -546,14 +541,18 @@ def test_create_model_all_params(self): # Set up parameter values base_model_id = 'testString' forced_glossary = io.BytesIO(b'This is a mock file.').getvalue() + forced_glossary_content_type = 'application/x-tmx+xml' parallel_corpus = io.BytesIO(b'This is a mock file.').getvalue() + parallel_corpus_content_type = 'application/x-tmx+xml' name = 'testString' # Invoke method response = _service.create_model( base_model_id, forced_glossary=forced_glossary, + forced_glossary_content_type=forced_glossary_content_type, parallel_corpus=parallel_corpus, + parallel_corpus_content_type=parallel_corpus_content_type, name=name, headers={} ) @@ -642,7 +641,6 @@ def test_create_model_value_error(self): with pytest.raises(ValueError): _service.create_model(**req_copy) - def test_create_model_value_error_with_retries(self): # Enable retries and run test_create_model_value_error. _service.enable_retries() @@ -719,7 +717,6 @@ def test_delete_model_value_error(self): with pytest.raises(ValueError): _service.delete_model(**req_copy) - def test_delete_model_value_error_with_retries(self): # Enable retries and run test_delete_model_value_error. _service.enable_retries() @@ -796,7 +793,6 @@ def test_get_model_value_error(self): with pytest.raises(ValueError): _service.get_model(**req_copy) - def test_get_model_value_error_with_retries(self): # Enable retries and run test_get_model_value_error. _service.enable_retries() @@ -874,7 +870,6 @@ def test_list_documents_value_error(self): with pytest.raises(ValueError): _service.list_documents(**req_copy) - def test_list_documents_value_error_with_retries(self): # Enable retries and run test_list_documents_value_error. _service.enable_retries() @@ -906,7 +901,7 @@ def test_translate_document_all_params(self): # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() filename = 'testString' - file_content_type = 'application/powerpoint' + file_content_type = 'application/mspowerpoint' model_id = 'testString' source = 'testString' target = 'testString' @@ -1002,7 +997,6 @@ def test_translate_document_value_error(self): with pytest.raises(ValueError): _service.translate_document(**req_copy) - def test_translate_document_value_error_with_retries(self): # Enable retries and run test_translate_document_value_error. _service.enable_retries() @@ -1079,7 +1073,6 @@ def test_get_document_status_value_error(self): with pytest.raises(ValueError): _service.get_document_status(**req_copy) - def test_get_document_status_value_error_with_retries(self): # Enable retries and run test_get_document_status_value_error. _service.enable_retries() @@ -1150,7 +1143,6 @@ def test_delete_document_value_error(self): with pytest.raises(ValueError): _service.delete_document(**req_copy) - def test_delete_document_value_error_with_retries(self): # Enable retries and run test_delete_document_value_error. _service.enable_retries() @@ -1265,7 +1257,6 @@ def test_get_translated_document_value_error(self): with pytest.raises(ValueError): _service.get_translated_document(**req_copy) - def test_get_translated_document_value_error_with_retries(self): # Enable retries and run test_get_translated_document_value_error. _service.enable_retries() diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index b00e2f23a..547082976 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ _service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' @@ -133,7 +133,6 @@ def test_analyze_all_params(self): sentiment_options_model = {} sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - sentiment_options_model['model'] = 'testString' # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} @@ -162,7 +161,7 @@ def test_analyze_all_params(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {} + features_model['metadata'] = {'foo': 'bar'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -277,7 +276,6 @@ def test_analyze_value_error(self): sentiment_options_model = {} sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - sentiment_options_model['model'] = 'testString' # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} @@ -306,7 +304,7 @@ def test_analyze_value_error(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {} + features_model['metadata'] = {'foo': 'bar'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -335,7 +333,6 @@ def test_analyze_value_error(self): with pytest.raises(ValueError): _service.analyze(**req_copy) - def test_analyze_value_error_with_retries(self): # Enable retries and run test_analyze_value_error. _service.enable_retries() @@ -413,7 +410,6 @@ def test_list_models_value_error(self): with pytest.raises(ValueError): _service.list_models(**req_copy) - def test_list_models_value_error_with_retries(self): # Enable retries and run test_list_models_value_error. _service.enable_retries() @@ -490,7 +486,6 @@ def test_delete_model_value_error(self): with pytest.raises(ValueError): _service.delete_model(**req_copy) - def test_delete_model_value_error_with_retries(self): # Enable retries and run test_delete_model_value_error. _service.enable_retries() @@ -505,502 +500,6 @@ def test_delete_model_value_error_with_retries(self): # End of Service: ManageModels ############################################################################## -############################################################################## -# Start of Service: ManageSentimentModels -############################################################################## -# region - -class TestCreateSentimentModel(): - """ - Test Class for create_sentiment_model - """ - - @responses.activate - def test_create_sentiment_model_all_params(self): - """ - create_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) - - # Set up parameter values - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - name = 'testString' - description = 'testString' - model_version = 'testString' - workspace_id = 'testString' - version_description = 'testString' - - # Invoke method - response = _service.create_sentiment_model( - language, - training_data, - name=name, - description=description, - model_version=model_version, - workspace_id=workspace_id, - version_description=version_description, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - - def test_create_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_create_sentiment_model_all_params. - _service.enable_retries() - self.test_create_sentiment_model_all_params() - - # Disable retries and run test_create_sentiment_model_all_params. - _service.disable_retries() - self.test_create_sentiment_model_all_params() - - @responses.activate - def test_create_sentiment_model_required_params(self): - """ - test_create_sentiment_model_required_params() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) - - # Set up parameter values - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.create_sentiment_model( - language, - training_data, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - - def test_create_sentiment_model_required_params_with_retries(self): - # Enable retries and run test_create_sentiment_model_required_params. - _service.enable_retries() - self.test_create_sentiment_model_required_params() - - # Disable retries and run test_create_sentiment_model_required_params. - _service.disable_retries() - self.test_create_sentiment_model_required_params() - - @responses.activate - def test_create_sentiment_model_value_error(self): - """ - test_create_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) - - # Set up parameter values - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "language": language, - "training_data": training_data, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_sentiment_model(**req_copy) - - - def test_create_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_create_sentiment_model_value_error. - _service.enable_retries() - self.test_create_sentiment_model_value_error() - - # Disable retries and run test_create_sentiment_model_value_error. - _service.disable_retries() - self.test_create_sentiment_model_value_error() - -class TestListSentimentModels(): - """ - Test Class for list_sentiment_models - """ - - @responses.activate - def test_list_sentiment_models_all_params(self): - """ - list_sentiment_models() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.list_sentiment_models() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_sentiment_models_all_params_with_retries(self): - # Enable retries and run test_list_sentiment_models_all_params. - _service.enable_retries() - self.test_list_sentiment_models_all_params() - - # Disable retries and run test_list_sentiment_models_all_params. - _service.disable_retries() - self.test_list_sentiment_models_all_params() - - @responses.activate - def test_list_sentiment_models_value_error(self): - """ - test_list_sentiment_models_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_sentiment_models(**req_copy) - - - def test_list_sentiment_models_value_error_with_retries(self): - # Enable retries and run test_list_sentiment_models_value_error. - _service.enable_retries() - self.test_list_sentiment_models_value_error() - - # Disable retries and run test_list_sentiment_models_value_error. - _service.disable_retries() - self.test_list_sentiment_models_value_error() - -class TestGetSentimentModel(): - """ - Test Class for get_sentiment_model - """ - - @responses.activate - def test_get_sentiment_model_all_params(self): - """ - get_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.get_sentiment_model( - model_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_get_sentiment_model_all_params. - _service.enable_retries() - self.test_get_sentiment_model_all_params() - - # Disable retries and run test_get_sentiment_model_all_params. - _service.disable_retries() - self.test_get_sentiment_model_all_params() - - @responses.activate - def test_get_sentiment_model_value_error(self): - """ - test_get_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_sentiment_model(**req_copy) - - - def test_get_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_get_sentiment_model_value_error. - _service.enable_retries() - self.test_get_sentiment_model_value_error() - - # Disable retries and run test_get_sentiment_model_value_error. - _service.disable_retries() - self.test_get_sentiment_model_value_error() - -class TestUpdateSentimentModel(): - """ - Test Class for update_sentiment_model - """ - - @responses.activate - def test_update_sentiment_model_all_params(self): - """ - update_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - name = 'testString' - description = 'testString' - model_version = 'testString' - workspace_id = 'testString' - version_description = 'testString' - - # Invoke method - response = _service.update_sentiment_model( - model_id, - language, - training_data, - name=name, - description=description, - model_version=model_version, - workspace_id=workspace_id, - version_description=version_description, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_update_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_update_sentiment_model_all_params. - _service.enable_retries() - self.test_update_sentiment_model_all_params() - - # Disable retries and run test_update_sentiment_model_all_params. - _service.disable_retries() - self.test_update_sentiment_model_all_params() - - @responses.activate - def test_update_sentiment_model_required_params(self): - """ - test_update_sentiment_model_required_params() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.update_sentiment_model( - model_id, - language, - training_data, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_update_sentiment_model_required_params_with_retries(self): - # Enable retries and run test_update_sentiment_model_required_params. - _service.enable_retries() - self.test_update_sentiment_model_required_params() - - # Disable retries and run test_update_sentiment_model_required_params. - _service.disable_retries() - self.test_update_sentiment_model_required_params() - - @responses.activate - def test_update_sentiment_model_value_error(self): - """ - test_update_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - "language": language, - "training_data": training_data, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_sentiment_model(**req_copy) - - - def test_update_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_update_sentiment_model_value_error. - _service.enable_retries() - self.test_update_sentiment_model_value_error() - - # Disable retries and run test_update_sentiment_model_value_error. - _service.disable_retries() - self.test_update_sentiment_model_value_error() - -class TestDeleteSentimentModel(): - """ - Test Class for delete_sentiment_model - """ - - @responses.activate - def test_delete_sentiment_model_all_params(self): - """ - delete_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.delete_sentiment_model( - model_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_delete_sentiment_model_all_params. - _service.enable_retries() - self.test_delete_sentiment_model_all_params() - - # Disable retries and run test_delete_sentiment_model_all_params. - _service.disable_retries() - self.test_delete_sentiment_model_all_params() - - @responses.activate - def test_delete_sentiment_model_value_error(self): - """ - test_delete_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_sentiment_model(**req_copy) - - - def test_delete_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_delete_sentiment_model_value_error. - _service.enable_retries() - self.test_delete_sentiment_model_value_error() - - # Disable retries and run test_delete_sentiment_model_value_error. - _service.disable_retries() - self.test_delete_sentiment_model_value_error() - -# endregion -############################################################################## -# End of Service: ManageSentimentModels -############################################################################## - ############################################################################## # Start of Service: ManageCategoriesModels ############################################################################## @@ -1018,7 +517,7 @@ def test_create_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1068,7 +567,7 @@ def test_create_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1078,11 +577,13 @@ def test_create_categories_model_required_params(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.create_categories_model( language, training_data, + training_data_content_type, headers={} ) @@ -1106,7 +607,7 @@ def test_create_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1116,18 +617,19 @@ def test_create_categories_model_value_error(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_categories_model(**req_copy) - def test_create_categories_model_value_error_with_retries(self): # Enable retries and run test_create_categories_model_value_error. _service.enable_retries() @@ -1149,7 +651,7 @@ def test_list_categories_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1180,7 +682,7 @@ def test_list_categories_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1195,7 +697,6 @@ def test_list_categories_models_value_error(self): with pytest.raises(ValueError): _service.list_categories_models(**req_copy) - def test_list_categories_models_value_error_with_retries(self): # Enable retries and run test_list_categories_models_value_error. _service.enable_retries() @@ -1217,7 +718,7 @@ def test_get_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1253,7 +754,7 @@ def test_get_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1272,7 +773,6 @@ def test_get_categories_model_value_error(self): with pytest.raises(ValueError): _service.get_categories_model(**req_copy) - def test_get_categories_model_value_error_with_retries(self): # Enable retries and run test_get_categories_model_value_error. _service.enable_retries() @@ -1294,7 +794,7 @@ def test_update_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1346,7 +846,7 @@ def test_update_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1357,12 +857,14 @@ def test_update_categories_model_required_params(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.update_categories_model( model_id, language, training_data, + training_data_content_type, headers={} ) @@ -1386,7 +888,7 @@ def test_update_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1397,19 +899,20 @@ def test_update_categories_model_value_error(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_categories_model(**req_copy) - def test_update_categories_model_value_error_with_retries(self): # Enable retries and run test_update_categories_model_value_error. _service.enable_retries() @@ -1486,7 +989,6 @@ def test_delete_categories_model_value_error(self): with pytest.raises(ValueError): _service.delete_categories_model(**req_copy) - def test_delete_categories_model_value_error_with_retries(self): # Enable retries and run test_delete_categories_model_value_error. _service.enable_retries() @@ -1518,13 +1020,17 @@ def test_create_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a ClassificationsTrainingParameters model + classifications_training_parameters_model = {} + classifications_training_parameters_model['model_type'] = 'single_label' + # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() @@ -1534,6 +1040,7 @@ def test_create_classifications_model_all_params(self): model_version = 'testString' workspace_id = 'testString' version_description = 'testString' + training_parameters = classifications_training_parameters_model # Invoke method response = _service.create_classifications_model( @@ -1545,6 +1052,7 @@ def test_create_classifications_model_all_params(self): model_version=model_version, workspace_id=workspace_id, version_description=version_description, + training_parameters=training_parameters, headers={} ) @@ -1568,7 +1076,7 @@ def test_create_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1578,11 +1086,13 @@ def test_create_classifications_model_required_params(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.create_classifications_model( language, training_data, + training_data_content_type, headers={} ) @@ -1606,7 +1116,7 @@ def test_create_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1616,18 +1126,19 @@ def test_create_classifications_model_value_error(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_classifications_model(**req_copy) - def test_create_classifications_model_value_error_with_retries(self): # Enable retries and run test_create_classifications_model_value_error. _service.enable_retries() @@ -1649,7 +1160,7 @@ def test_list_classifications_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1680,7 +1191,7 @@ def test_list_classifications_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1695,7 +1206,6 @@ def test_list_classifications_models_value_error(self): with pytest.raises(ValueError): _service.list_classifications_models(**req_copy) - def test_list_classifications_models_value_error_with_retries(self): # Enable retries and run test_list_classifications_models_value_error. _service.enable_retries() @@ -1717,7 +1227,7 @@ def test_get_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1753,7 +1263,7 @@ def test_get_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1772,7 +1282,6 @@ def test_get_classifications_model_value_error(self): with pytest.raises(ValueError): _service.get_classifications_model(**req_copy) - def test_get_classifications_model_value_error_with_retries(self): # Enable retries and run test_get_classifications_model_value_error. _service.enable_retries() @@ -1794,13 +1303,17 @@ def test_update_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a ClassificationsTrainingParameters model + classifications_training_parameters_model = {} + classifications_training_parameters_model['model_type'] = 'single_label' + # Set up parameter values model_id = 'testString' language = 'testString' @@ -1811,6 +1324,7 @@ def test_update_classifications_model_all_params(self): model_version = 'testString' workspace_id = 'testString' version_description = 'testString' + training_parameters = classifications_training_parameters_model # Invoke method response = _service.update_classifications_model( @@ -1823,6 +1337,7 @@ def test_update_classifications_model_all_params(self): model_version=model_version, workspace_id=workspace_id, version_description=version_description, + training_parameters=training_parameters, headers={} ) @@ -1846,7 +1361,7 @@ def test_update_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1857,12 +1372,14 @@ def test_update_classifications_model_required_params(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.update_classifications_model( model_id, language, training_data, + training_data_content_type, headers={} ) @@ -1886,7 +1403,7 @@ def test_update_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1897,19 +1414,20 @@ def test_update_classifications_model_value_error(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_classifications_model(**req_copy) - def test_update_classifications_model_value_error_with_retries(self): # Enable retries and run test_update_classifications_model_value_error. _service.enable_retries() @@ -1986,7 +1504,6 @@ def test_delete_classifications_model_value_error(self): with pytest.raises(ValueError): _service.delete_classifications_model(**req_copy) - def test_delete_classifications_model_value_error_with_retries(self): # Enable retries and run test_delete_classifications_model_value_error. _service.enable_retries() @@ -2283,12 +1800,11 @@ def test_categories_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a CategoriesModel model categories_model_model_json = {} categories_model_model_json['name'] = 'testString' - categories_model_model_json['user_metadata'] = {} + categories_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} categories_model_model_json['language'] = 'testString' categories_model_model_json['description'] = 'testString' categories_model_model_json['model_version'] = 'testString' @@ -2330,11 +1846,10 @@ def test_categories_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' categories_model_model = {} # CategoriesModel categories_model_model['name'] = 'testString' - categories_model_model['user_metadata'] = {} + categories_model_model['user_metadata'] = {'key1': 'unknown type: dict'} categories_model_model['language'] = 'testString' categories_model_model['description'] = 'testString' categories_model_model['model_version'] = 'testString' @@ -2513,12 +2028,11 @@ def test_classifications_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a ClassificationsModel model classifications_model_model_json = {} classifications_model_model_json['name'] = 'testString' - classifications_model_model_json['user_metadata'] = {} + classifications_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} classifications_model_model_json['language'] = 'testString' classifications_model_model_json['description'] = 'testString' classifications_model_model_json['model_version'] = 'testString' @@ -2560,11 +2074,10 @@ def test_classifications_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' classifications_model_model = {} # ClassificationsModel classifications_model_model['name'] = 'testString' - classifications_model_model['user_metadata'] = {} + classifications_model_model['user_metadata'] = {'key1': 'unknown type: dict'} classifications_model_model['language'] = 'testString' classifications_model_model['description'] = 'testString' classifications_model_model['model_version'] = 'testString' @@ -2656,6 +2169,35 @@ def test_classifications_result_serialization(self): classifications_result_model_json2 = classifications_result_model.to_dict() assert classifications_result_model_json2 == classifications_result_model_json +class TestModel_ClassificationsTrainingParameters(): + """ + Test Class for ClassificationsTrainingParameters + """ + + def test_classifications_training_parameters_serialization(self): + """ + Test serialization/deserialization for ClassificationsTrainingParameters + """ + + # Construct a json representation of a ClassificationsTrainingParameters model + classifications_training_parameters_model_json = {} + classifications_training_parameters_model_json['model_type'] = 'single_label' + + # Construct a model instance of ClassificationsTrainingParameters by calling from_dict on the json representation + classifications_training_parameters_model = ClassificationsTrainingParameters.from_dict(classifications_training_parameters_model_json) + assert classifications_training_parameters_model != False + + # Construct a model instance of ClassificationsTrainingParameters by calling from_dict on the json representation + classifications_training_parameters_model_dict = ClassificationsTrainingParameters.from_dict(classifications_training_parameters_model_json).__dict__ + classifications_training_parameters_model2 = ClassificationsTrainingParameters(**classifications_training_parameters_model_dict) + + # Verify the model instances are equivalent + assert classifications_training_parameters_model == classifications_training_parameters_model2 + + # Convert model instance back to dict and verify no loss of data + classifications_training_parameters_model_json2 = classifications_training_parameters_model.to_dict() + assert classifications_training_parameters_model_json2 == classifications_training_parameters_model_json + class TestModel_ConceptsOptions(): """ Test Class for ConceptsOptions @@ -3150,7 +2692,6 @@ def test_features_serialization(self): sentiment_options_model = {} # SentimentOptions sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - sentiment_options_model['model'] = 'testString' summarization_options_model = {} # SummarizationOptions summarization_options_model['limit'] = 10 @@ -3175,7 +2716,7 @@ def test_features_serialization(self): features_model_json['emotion'] = emotion_options_model features_model_json['entities'] = entities_options_model features_model_json['keywords'] = keywords_options_model - features_model_json['metadata'] = {} + features_model_json['metadata'] = {'foo': 'bar'} features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model @@ -3386,56 +2927,6 @@ def test_list_models_results_serialization(self): list_models_results_model_json2 = list_models_results_model.to_dict() assert list_models_results_model_json2 == list_models_results_model_json -class TestModel_ListSentimentModelsResponse(): - """ - Test Class for ListSentimentModelsResponse - """ - - def test_list_sentiment_models_response_serialization(self): - """ - Test serialization/deserialization for ListSentimentModelsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' - - sentiment_model_model = {} # SentimentModel - sentiment_model_model['features'] = ['testString'] - sentiment_model_model['status'] = 'starting' - sentiment_model_model['model_id'] = 'testString' - sentiment_model_model['created'] = '2019-01-01T12:00:00Z' - sentiment_model_model['last_trained'] = '2019-01-01T12:00:00Z' - sentiment_model_model['last_deployed'] = '2019-01-01T12:00:00Z' - sentiment_model_model['name'] = 'testString' - sentiment_model_model['user_metadata'] = {} - sentiment_model_model['language'] = 'testString' - sentiment_model_model['description'] = 'testString' - sentiment_model_model['model_version'] = 'testString' - sentiment_model_model['notices'] = [notice_model] - sentiment_model_model['workspace_id'] = 'testString' - sentiment_model_model['version_description'] = 'testString' - - # Construct a json representation of a ListSentimentModelsResponse model - list_sentiment_models_response_model_json = {} - list_sentiment_models_response_model_json['models'] = [sentiment_model_model] - - # Construct a model instance of ListSentimentModelsResponse by calling from_dict on the json representation - list_sentiment_models_response_model = ListSentimentModelsResponse.from_dict(list_sentiment_models_response_model_json) - assert list_sentiment_models_response_model != False - - # Construct a model instance of ListSentimentModelsResponse by calling from_dict on the json representation - list_sentiment_models_response_model_dict = ListSentimentModelsResponse.from_dict(list_sentiment_models_response_model_json).__dict__ - list_sentiment_models_response_model2 = ListSentimentModelsResponse(**list_sentiment_models_response_model_dict) - - # Verify the model instances are equivalent - assert list_sentiment_models_response_model == list_sentiment_models_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_sentiment_models_response_model_json2 = list_sentiment_models_response_model.to_dict() - assert list_sentiment_models_response_model_json2 == list_sentiment_models_response_model_json - class TestModel_Model(): """ Test Class for Model @@ -3485,7 +2976,6 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} - notice_model_json['message'] = 'testString' # Construct a model instance of Notice by calling from_dict on the json representation notice_model = Notice.from_dict(notice_model_json) @@ -3962,53 +3452,6 @@ def test_sentence_result_serialization(self): sentence_result_model_json2 = sentence_result_model.to_dict() assert sentence_result_model_json2 == sentence_result_model_json -class TestModel_SentimentModel(): - """ - Test Class for SentimentModel - """ - - def test_sentiment_model_serialization(self): - """ - Test serialization/deserialization for SentimentModel - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' - - # Construct a json representation of a SentimentModel model - sentiment_model_model_json = {} - sentiment_model_model_json['features'] = ['testString'] - sentiment_model_model_json['status'] = 'starting' - sentiment_model_model_json['model_id'] = 'testString' - sentiment_model_model_json['created'] = '2019-01-01T12:00:00Z' - sentiment_model_model_json['last_trained'] = '2019-01-01T12:00:00Z' - sentiment_model_model_json['last_deployed'] = '2019-01-01T12:00:00Z' - sentiment_model_model_json['name'] = 'testString' - sentiment_model_model_json['user_metadata'] = {} - sentiment_model_model_json['language'] = 'testString' - sentiment_model_model_json['description'] = 'testString' - sentiment_model_model_json['model_version'] = 'testString' - sentiment_model_model_json['notices'] = [notice_model] - sentiment_model_model_json['workspace_id'] = 'testString' - sentiment_model_model_json['version_description'] = 'testString' - - # Construct a model instance of SentimentModel by calling from_dict on the json representation - sentiment_model_model = SentimentModel.from_dict(sentiment_model_model_json) - assert sentiment_model_model != False - - # Construct a model instance of SentimentModel by calling from_dict on the json representation - sentiment_model_model_dict = SentimentModel.from_dict(sentiment_model_model_json).__dict__ - sentiment_model_model2 = SentimentModel(**sentiment_model_model_dict) - - # Verify the model instances are equivalent - assert sentiment_model_model == sentiment_model_model2 - - # Convert model instance back to dict and verify no loss of data - sentiment_model_model_json2 = sentiment_model_model.to_dict() - assert sentiment_model_model_json2 == sentiment_model_model_json - class TestModel_SentimentOptions(): """ Test Class for SentimentOptions @@ -4023,7 +3466,6 @@ def test_sentiment_options_serialization(self): sentiment_options_model_json = {} sentiment_options_model_json['document'] = True sentiment_options_model_json['targets'] = ['testString'] - sentiment_options_model_json['model'] = 'testString' # Construct a model instance of SentimentOptions by calling from_dict on the json representation sentiment_options_model = SentimentOptions.from_dict(sentiment_options_model_json) diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py old mode 100755 new mode 100644 index ee6bc39b0..b2578b8f3 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ def test_get_model_all_params(self): get_model() """ # Set up mock - url = preprocess_url('/v1/models/ar-AR_BroadbandModel') + url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, @@ -125,7 +125,7 @@ def test_get_model_all_params(self): status=200) # Set up parameter values - model_id = 'ar-AR_BroadbandModel' + model_id = 'ar-MS_BroadbandModel' # Invoke method response = _service.get_model( @@ -152,7 +152,7 @@ def test_get_model_value_error(self): test_get_model_value_error() """ # Set up mock - url = preprocess_url('/v1/models/ar-AR_BroadbandModel') + url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, @@ -161,7 +161,7 @@ def test_get_model_value_error(self): status=200) # Set up parameter values - model_id = 'ar-AR_BroadbandModel' + model_id = 'ar-MS_BroadbandModel' # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -172,7 +172,6 @@ def test_get_model_value_error(self): with pytest.raises(ValueError): _service.get_model(**req_copy) - def test_get_model_value_error_with_retries(self): # Enable retries and run test_get_model_value_error. _service.enable_retries() @@ -221,23 +220,23 @@ def test_recognize_all_params(self): customization_weight = 72.5 inactivity_timeout = 38 keywords = ['testString'] - keywords_threshold = 72.5 + keywords_threshold = 36.0 max_alternatives = 38 - word_alternatives_threshold = 72.5 + word_alternatives_threshold = 36.0 word_confidence = False timestamps = False profanity_filter = True smart_formatting = False speaker_labels = False - customization_id = 'testString' grammar_name = 'testString' redaction = False audio_metrics = False end_of_phrase_silence_time = 72.5 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 72.5 - background_audio_suppression = 72.5 + speech_detector_sensitivity = 36.0 + background_audio_suppression = 36.0 low_latency = False + character_insertion_bias = 36.0 # Invoke method response = _service.recognize( @@ -258,7 +257,6 @@ def test_recognize_all_params(self): profanity_filter=profanity_filter, smart_formatting=smart_formatting, speaker_labels=speaker_labels, - customization_id=customization_id, grammar_name=grammar_name, redaction=redaction, audio_metrics=audio_metrics, @@ -267,6 +265,7 @@ def test_recognize_all_params(self): speech_detector_sensitivity=speech_detector_sensitivity, background_audio_suppression=background_audio_suppression, low_latency=low_latency, + character_insertion_bias=character_insertion_bias, headers={} ) @@ -283,22 +282,17 @@ def test_recognize_all_params(self): assert 'customization_weight={}'.format(customization_weight) in query_string assert 'inactivity_timeout={}'.format(inactivity_timeout) in query_string assert 'keywords={}'.format(','.join(keywords)) in query_string - assert 'keywords_threshold={}'.format(keywords_threshold) in query_string assert 'max_alternatives={}'.format(max_alternatives) in query_string - assert 'word_alternatives_threshold={}'.format(word_alternatives_threshold) in query_string assert 'word_confidence={}'.format('true' if word_confidence else 'false') in query_string assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string - assert 'customization_id={}'.format(customization_id) in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string - assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string - assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params @@ -374,7 +368,6 @@ def test_recognize_value_error(self): with pytest.raises(ValueError): _service.recognize(**req_copy) - def test_recognize_value_error_with_retries(self): # Enable retries and run test_recognize_value_error. _service.enable_retries() @@ -508,7 +501,6 @@ def test_register_callback_value_error(self): with pytest.raises(ValueError): _service.register_callback(**req_copy) - def test_register_callback_value_error_with_retries(self): # Enable retries and run test_register_callback_value_error. _service.enable_retries() @@ -583,7 +575,6 @@ def test_unregister_callback_value_error(self): with pytest.raises(ValueError): _service.unregister_callback(**req_copy) - def test_unregister_callback_value_error_with_retries(self): # Enable retries and run test_unregister_callback_value_error. _service.enable_retries() @@ -626,25 +617,25 @@ def test_create_job_all_params(self): customization_weight = 72.5 inactivity_timeout = 38 keywords = ['testString'] - keywords_threshold = 72.5 + keywords_threshold = 36.0 max_alternatives = 38 - word_alternatives_threshold = 72.5 + word_alternatives_threshold = 36.0 word_confidence = False timestamps = False profanity_filter = True smart_formatting = False speaker_labels = False - customization_id = 'testString' grammar_name = 'testString' redaction = False processing_metrics = False - processing_metrics_interval = 72.5 + processing_metrics_interval = 36.0 audio_metrics = False end_of_phrase_silence_time = 72.5 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 72.5 - background_audio_suppression = 72.5 + speech_detector_sensitivity = 36.0 + background_audio_suppression = 36.0 low_latency = False + character_insertion_bias = 36.0 # Invoke method response = _service.create_job( @@ -669,7 +660,6 @@ def test_create_job_all_params(self): profanity_filter=profanity_filter, smart_formatting=smart_formatting, speaker_labels=speaker_labels, - customization_id=customization_id, grammar_name=grammar_name, redaction=redaction, processing_metrics=processing_metrics, @@ -680,6 +670,7 @@ def test_create_job_all_params(self): speech_detector_sensitivity=speech_detector_sensitivity, background_audio_suppression=background_audio_suppression, low_latency=low_latency, + character_insertion_bias=character_insertion_bias, headers={} ) @@ -700,24 +691,18 @@ def test_create_job_all_params(self): assert 'customization_weight={}'.format(customization_weight) in query_string assert 'inactivity_timeout={}'.format(inactivity_timeout) in query_string assert 'keywords={}'.format(','.join(keywords)) in query_string - assert 'keywords_threshold={}'.format(keywords_threshold) in query_string assert 'max_alternatives={}'.format(max_alternatives) in query_string - assert 'word_alternatives_threshold={}'.format(word_alternatives_threshold) in query_string assert 'word_confidence={}'.format('true' if word_confidence else 'false') in query_string assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string - assert 'customization_id={}'.format(customization_id) in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string assert 'processing_metrics={}'.format('true' if processing_metrics else 'false') in query_string - assert 'processing_metrics_interval={}'.format(processing_metrics_interval) in query_string assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string - assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string - assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params @@ -793,7 +778,6 @@ def test_create_job_value_error(self): with pytest.raises(ValueError): _service.create_job(**req_copy) - def test_create_job_value_error_with_retries(self): # Enable retries and run test_create_job_value_error. _service.enable_retries() @@ -906,7 +890,6 @@ def test_check_job_value_error(self): with pytest.raises(ValueError): _service.check_job(**req_copy) - def test_check_job_value_error_with_retries(self): # Enable retries and run test_check_job_value_error. _service.enable_retries() @@ -977,7 +960,6 @@ def test_delete_job_value_error(self): with pytest.raises(ValueError): _service.delete_job(**req_copy) - def test_delete_job_value_error_with_retries(self): # Enable retries and run test_delete_job_value_error. _service.enable_retries() @@ -1080,7 +1062,6 @@ def test_create_language_model_value_error(self): with pytest.raises(ValueError): _service.create_language_model(**req_copy) - def test_create_language_model_value_error_with_retries(self): # Enable retries and run test_create_language_model_value_error. _service.enable_retries() @@ -1110,7 +1091,7 @@ def test_list_language_models_all_params(self): status=200) # Set up parameter values - language = 'ar-AR' + language = 'ar-MS' # Invoke method response = _service.list_language_models( @@ -1233,7 +1214,6 @@ def test_get_language_model_value_error(self): with pytest.raises(ValueError): _service.get_language_model(**req_copy) - def test_get_language_model_value_error_with_retries(self): # Enable retries and run test_get_language_model_value_error. _service.enable_retries() @@ -1304,7 +1284,6 @@ def test_delete_language_model_value_error(self): with pytest.raises(ValueError): _service.delete_language_model(**req_copy) - def test_delete_language_model_value_error_with_retries(self): # Enable retries and run test_delete_language_model_value_error. _service.enable_retries() @@ -1337,12 +1316,14 @@ def test_train_language_model_all_params(self): customization_id = 'testString' word_type_to_add = 'all' customization_weight = 72.5 + strict = True # Invoke method response = _service.train_language_model( customization_id, word_type_to_add=word_type_to_add, customization_weight=customization_weight, + strict=strict, headers={} ) @@ -1354,6 +1335,7 @@ def test_train_language_model_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'word_type_to_add={}'.format(word_type_to_add) in query_string assert 'customization_weight={}'.format(customization_weight) in query_string + assert 'strict={}'.format('true' if strict else 'false') in query_string def test_train_language_model_all_params_with_retries(self): # Enable retries and run test_train_language_model_all_params. @@ -1426,7 +1408,6 @@ def test_train_language_model_value_error(self): with pytest.raises(ValueError): _service.train_language_model(**req_copy) - def test_train_language_model_value_error_with_retries(self): # Enable retries and run test_train_language_model_value_error. _service.enable_retries() @@ -1497,7 +1478,6 @@ def test_reset_language_model_value_error(self): with pytest.raises(ValueError): _service.reset_language_model(**req_copy) - def test_reset_language_model_value_error_with_retries(self): # Enable retries and run test_reset_language_model_value_error. _service.enable_retries() @@ -1568,7 +1548,6 @@ def test_upgrade_language_model_value_error(self): with pytest.raises(ValueError): _service.upgrade_language_model(**req_copy) - def test_upgrade_language_model_value_error_with_retries(self): # Enable retries and run test_upgrade_language_model_value_error. _service.enable_retries() @@ -1655,7 +1634,6 @@ def test_list_corpora_value_error(self): with pytest.raises(ValueError): _service.list_corpora(**req_copy) - def test_list_corpora_value_error_with_retries(self): # Enable retries and run test_list_corpora_value_error. _service.enable_retries() @@ -1777,7 +1755,6 @@ def test_add_corpus_value_error(self): with pytest.raises(ValueError): _service.add_corpus(**req_copy) - def test_add_corpus_value_error_with_retries(self): # Enable retries and run test_add_corpus_value_error. _service.enable_retries() @@ -1858,7 +1835,6 @@ def test_get_corpus_value_error(self): with pytest.raises(ValueError): _service.get_corpus(**req_copy) - def test_get_corpus_value_error_with_retries(self): # Enable retries and run test_get_corpus_value_error. _service.enable_retries() @@ -1933,7 +1909,6 @@ def test_delete_corpus_value_error(self): with pytest.raises(ValueError): _service.delete_corpus(**req_copy) - def test_delete_corpus_value_error_with_retries(self): # Enable retries and run test_delete_corpus_value_error. _service.enable_retries() @@ -2065,7 +2040,6 @@ def test_list_words_value_error(self): with pytest.raises(ValueError): _service.list_words(**req_copy) - def test_list_words_value_error_with_retries(self): # Enable retries and run test_list_words_value_error. _service.enable_retries() @@ -2155,7 +2129,6 @@ def test_add_words_value_error(self): with pytest.raises(ValueError): _service.add_words(**req_copy) - def test_add_words_value_error_with_retries(self): # Enable retries and run test_add_words_value_error. _service.enable_retries() @@ -2244,7 +2217,6 @@ def test_add_word_value_error(self): with pytest.raises(ValueError): _service.add_word(**req_copy) - def test_add_word_value_error_with_retries(self): # Enable retries and run test_add_word_value_error. _service.enable_retries() @@ -2325,7 +2297,6 @@ def test_get_word_value_error(self): with pytest.raises(ValueError): _service.get_word(**req_copy) - def test_get_word_value_error_with_retries(self): # Enable retries and run test_get_word_value_error. _service.enable_retries() @@ -2400,7 +2371,6 @@ def test_delete_word_value_error(self): with pytest.raises(ValueError): _service.delete_word(**req_copy) - def test_delete_word_value_error_with_retries(self): # Enable retries and run test_delete_word_value_error. _service.enable_retries() @@ -2487,7 +2457,6 @@ def test_list_grammars_value_error(self): with pytest.raises(ValueError): _service.list_grammars(**req_copy) - def test_list_grammars_value_error_with_retries(self): # Enable retries and run test_list_grammars_value_error. _service.enable_retries() @@ -2617,7 +2586,6 @@ def test_add_grammar_value_error(self): with pytest.raises(ValueError): _service.add_grammar(**req_copy) - def test_add_grammar_value_error_with_retries(self): # Enable retries and run test_add_grammar_value_error. _service.enable_retries() @@ -2698,7 +2666,6 @@ def test_get_grammar_value_error(self): with pytest.raises(ValueError): _service.get_grammar(**req_copy) - def test_get_grammar_value_error_with_retries(self): # Enable retries and run test_get_grammar_value_error. _service.enable_retries() @@ -2773,7 +2740,6 @@ def test_delete_grammar_value_error(self): with pytest.raises(ValueError): _service.delete_grammar(**req_copy) - def test_delete_grammar_value_error_with_retries(self): # Enable retries and run test_delete_grammar_value_error. _service.enable_retries() @@ -2814,7 +2780,7 @@ def test_create_acoustic_model_all_params(self): # Set up parameter values name = 'testString' - base_model_name = 'ar-AR_BroadbandModel' + base_model_name = 'ar-MS_BroadbandModel' description = 'testString' # Invoke method @@ -2831,7 +2797,7 @@ def test_create_acoustic_model_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['base_model_name'] == 'ar-AR_BroadbandModel' + assert req_body['base_model_name'] == 'ar-MS_BroadbandModel' assert req_body['description'] == 'testString' def test_create_acoustic_model_all_params_with_retries(self): @@ -2859,7 +2825,7 @@ def test_create_acoustic_model_value_error(self): # Set up parameter values name = 'testString' - base_model_name = 'ar-AR_BroadbandModel' + base_model_name = 'ar-MS_BroadbandModel' description = 'testString' # Pass in all but one required param and check for a ValueError @@ -2872,7 +2838,6 @@ def test_create_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.create_acoustic_model(**req_copy) - def test_create_acoustic_model_value_error_with_retries(self): # Enable retries and run test_create_acoustic_model_value_error. _service.enable_retries() @@ -2902,7 +2867,7 @@ def test_list_acoustic_models_all_params(self): status=200) # Set up parameter values - language = 'ar-AR' + language = 'ar-MS' # Invoke method response = _service.list_acoustic_models( @@ -3025,7 +2990,6 @@ def test_get_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.get_acoustic_model(**req_copy) - def test_get_acoustic_model_value_error_with_retries(self): # Enable retries and run test_get_acoustic_model_value_error. _service.enable_retries() @@ -3096,7 +3060,6 @@ def test_delete_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.delete_acoustic_model(**req_copy) - def test_delete_acoustic_model_value_error_with_retries(self): # Enable retries and run test_delete_acoustic_model_value_error. _service.enable_retries() @@ -3128,11 +3091,13 @@ def test_train_acoustic_model_all_params(self): # Set up parameter values customization_id = 'testString' custom_language_model_id = 'testString' + strict = True # Invoke method response = _service.train_acoustic_model( customization_id, custom_language_model_id=custom_language_model_id, + strict=strict, headers={} ) @@ -3143,6 +3108,7 @@ def test_train_acoustic_model_all_params(self): query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string + assert 'strict={}'.format('true' if strict else 'false') in query_string def test_train_acoustic_model_all_params_with_retries(self): # Enable retries and run test_train_acoustic_model_all_params. @@ -3215,7 +3181,6 @@ def test_train_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.train_acoustic_model(**req_copy) - def test_train_acoustic_model_value_error_with_retries(self): # Enable retries and run test_train_acoustic_model_value_error. _service.enable_retries() @@ -3286,7 +3251,6 @@ def test_reset_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.reset_acoustic_model(**req_copy) - def test_reset_acoustic_model_value_error_with_retries(self): # Enable retries and run test_reset_acoustic_model_value_error. _service.enable_retries() @@ -3399,7 +3363,6 @@ def test_upgrade_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.upgrade_acoustic_model(**req_copy) - def test_upgrade_acoustic_model_value_error_with_retries(self): # Enable retries and run test_upgrade_acoustic_model_value_error. _service.enable_retries() @@ -3486,7 +3449,6 @@ def test_list_audio_value_error(self): with pytest.raises(ValueError): _service.list_audio(**req_copy) - def test_list_audio_value_error_with_retries(self): # Enable retries and run test_list_audio_value_error. _service.enable_retries() @@ -3614,7 +3576,6 @@ def test_add_audio_value_error(self): with pytest.raises(ValueError): _service.add_audio(**req_copy) - def test_add_audio_value_error_with_retries(self): # Enable retries and run test_add_audio_value_error. _service.enable_retries() @@ -3695,7 +3656,6 @@ def test_get_audio_value_error(self): with pytest.raises(ValueError): _service.get_audio(**req_copy) - def test_get_audio_value_error_with_retries(self): # Enable retries and run test_get_audio_value_error. _service.enable_retries() @@ -3770,7 +3730,6 @@ def test_delete_audio_value_error(self): with pytest.raises(ValueError): _service.delete_audio(**req_copy) - def test_delete_audio_value_error_with_retries(self): # Enable retries and run test_delete_audio_value_error. _service.enable_retries() @@ -3855,7 +3814,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -4053,16 +4011,16 @@ def test_audio_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] @@ -4070,7 +4028,7 @@ def test_audio_metrics_serialization(self): # Construct a json representation of a AudioMetrics model audio_metrics_model_json = {} - audio_metrics_model_json['sampling_interval'] = 72.5 + audio_metrics_model_json['sampling_interval'] = 36.0 audio_metrics_model_json['accumulated'] = audio_metrics_details_model # Construct a model instance of AudioMetrics by calling from_dict on the json representation @@ -4101,17 +4059,17 @@ def test_audio_metrics_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 # Construct a json representation of a AudioMetricsDetails model audio_metrics_details_model_json = {} audio_metrics_details_model_json['final'] = True - audio_metrics_details_model_json['end_time'] = 72.5 - audio_metrics_details_model_json['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model_json['speech_ratio'] = 72.5 - audio_metrics_details_model_json['high_frequency_loss'] = 72.5 + audio_metrics_details_model_json['end_time'] = 36.0 + audio_metrics_details_model_json['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model_json['speech_ratio'] = 36.0 + audio_metrics_details_model_json['high_frequency_loss'] = 36.0 audio_metrics_details_model_json['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model_json['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model_json['speech_level'] = [audio_metrics_histogram_bin_model] @@ -4144,8 +4102,8 @@ def test_audio_metrics_histogram_bin_serialization(self): # Construct a json representation of a AudioMetricsHistogramBin model audio_metrics_histogram_bin_model_json = {} - audio_metrics_histogram_bin_model_json['begin'] = 72.5 - audio_metrics_histogram_bin_model_json['end'] = 72.5 + audio_metrics_histogram_bin_model_json['begin'] = 36.0 + audio_metrics_histogram_bin_model_json['end'] = 36.0 audio_metrics_histogram_bin_model_json['count'] = 38 # Construct a model instance of AudioMetricsHistogramBin by calling from_dict on the json representation @@ -4551,10 +4509,10 @@ def test_processed_audio_serialization(self): # Construct a json representation of a ProcessedAudio model processed_audio_model_json = {} - processed_audio_model_json['received'] = 72.5 - processed_audio_model_json['seen_by_engine'] = 72.5 - processed_audio_model_json['transcription'] = 72.5 - processed_audio_model_json['speaker_labels'] = 72.5 + processed_audio_model_json['received'] = 36.0 + processed_audio_model_json['seen_by_engine'] = 36.0 + processed_audio_model_json['transcription'] = 36.0 + processed_audio_model_json['speaker_labels'] = 36.0 # Construct a model instance of ProcessedAudio by calling from_dict on the json representation processed_audio_model = ProcessedAudio.from_dict(processed_audio_model_json) @@ -4584,15 +4542,15 @@ def test_processing_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 # Construct a json representation of a ProcessingMetrics model processing_metrics_model_json = {} processing_metrics_model_json['processed_audio'] = processed_audio_model - processing_metrics_model_json['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model_json['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model_json['periodic'] = True # Construct a model instance of ProcessingMetrics by calling from_dict on the json representation @@ -4646,46 +4604,46 @@ def test_recognition_job_serialization(self): speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' speaker_labels_result_model = {} # SpeakerLabelsResult - speaker_labels_result_model['from'] = 72.5 - speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['from'] = 36.0 + speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 - speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model - processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_model = {} # AudioMetrics - audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model speech_recognition_results_model = {} # SpeechRecognitionResults @@ -4758,46 +4716,46 @@ def test_recognition_jobs_serialization(self): speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' speaker_labels_result_model = {} # SpeakerLabelsResult - speaker_labels_result_model['from'] = 72.5 - speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['from'] = 36.0 + speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 - speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model - processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_model = {} # AudioMetrics - audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model speech_recognition_results_model = {} # SpeechRecognitionResults @@ -4879,10 +4837,10 @@ def test_speaker_labels_result_serialization(self): # Construct a json representation of a SpeakerLabelsResult model speaker_labels_result_model_json = {} - speaker_labels_result_model_json['from'] = 72.5 - speaker_labels_result_model_json['to'] = 72.5 + speaker_labels_result_model_json['from'] = 36.0 + speaker_labels_result_model_json['to'] = 36.0 speaker_labels_result_model_json['speaker'] = 38 - speaker_labels_result_model_json['confidence'] = 72.5 + speaker_labels_result_model_json['confidence'] = 36.0 speaker_labels_result_model_json['final'] = True # Construct a model instance of SpeakerLabelsResult by calling from_dict on the json representation @@ -5056,7 +5014,7 @@ def test_speech_recognition_result_serialization(self): speech_recognition_result_model_json = {} speech_recognition_result_model_json['final'] = True speech_recognition_result_model_json['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model_json['keywords_result'] = {} + speech_recognition_result_model_json['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model_json['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model_json['end_of_utterance'] = 'end_of_data' @@ -5111,46 +5069,46 @@ def test_speech_recognition_results_serialization(self): speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' speaker_labels_result_model = {} # SpeakerLabelsResult - speaker_labels_result_model['from'] = 72.5 - speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['from'] = 36.0 + speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 - speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model - processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_model = {} # AudioMetrics - audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model # Construct a json representation of a SpeechRecognitionResults model diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 25ab220d2..9d3d8c252 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ def test_get_voice_all_params(self): get_voice() """ # Set up mock - url = preprocess_url('/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -125,7 +125,7 @@ def test_get_voice_all_params(self): status=200) # Set up parameter values - voice = 'ar-AR_OmarVoice' + voice = 'ar-MS_OmarVoice' customization_id = 'testString' # Invoke method @@ -158,7 +158,7 @@ def test_get_voice_required_params(self): test_get_voice_required_params() """ # Set up mock - url = preprocess_url('/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -167,7 +167,7 @@ def test_get_voice_required_params(self): status=200) # Set up parameter values - voice = 'ar-AR_OmarVoice' + voice = 'ar-MS_OmarVoice' # Invoke method response = _service.get_voice( @@ -194,7 +194,7 @@ def test_get_voice_value_error(self): test_get_voice_value_error() """ # Set up mock - url = preprocess_url('/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -203,7 +203,7 @@ def test_get_voice_value_error(self): status=200) # Set up parameter values - voice = 'ar-AR_OmarVoice' + voice = 'ar-MS_OmarVoice' # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -214,7 +214,6 @@ def test_get_voice_value_error(self): with pytest.raises(ValueError): _service.get_voice(**req_copy) - def test_get_voice_value_error_with_retries(self): # Enable retries and run test_get_voice_value_error. _service.enable_retries() @@ -250,7 +249,7 @@ def test_synthesize_all_params(self): responses.add(responses.POST, url, body=mock_response, - content_type='audio/basic', + content_type='audio/alaw', status=200) # Set up parameter values @@ -258,6 +257,9 @@ def test_synthesize_all_params(self): accept = 'audio/ogg;codecs=opus' voice = 'en-US_MichaelV3Voice' customization_id = 'testString' + spell_out_mode = 'default' + rate_percentage = 38 + pitch_percentage = 38 # Invoke method response = _service.synthesize( @@ -265,6 +267,9 @@ def test_synthesize_all_params(self): accept=accept, voice=voice, customization_id=customization_id, + spell_out_mode=spell_out_mode, + rate_percentage=rate_percentage, + pitch_percentage=pitch_percentage, headers={} ) @@ -276,6 +281,9 @@ def test_synthesize_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'voice={}'.format(voice) in query_string assert 'customization_id={}'.format(customization_id) in query_string + assert 'spell_out_mode={}'.format(spell_out_mode) in query_string + assert 'rate_percentage={}'.format(rate_percentage) in query_string + assert 'pitch_percentage={}'.format(pitch_percentage) in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' @@ -300,7 +308,7 @@ def test_synthesize_required_params(self): responses.add(responses.POST, url, body=mock_response, - content_type='audio/basic', + content_type='audio/alaw', status=200) # Set up parameter values @@ -339,7 +347,7 @@ def test_synthesize_value_error(self): responses.add(responses.POST, url, body=mock_response, - content_type='audio/basic', + content_type='audio/alaw', status=200) # Set up parameter values @@ -354,7 +362,6 @@ def test_synthesize_value_error(self): with pytest.raises(ValueError): _service.synthesize(**req_copy) - def test_synthesize_value_error_with_retries(self): # Enable retries and run test_synthesize_value_error. _service.enable_retries() @@ -494,7 +501,6 @@ def test_get_pronunciation_value_error(self): with pytest.raises(ValueError): _service.get_pronunciation(**req_copy) - def test_get_pronunciation_value_error_with_retries(self): # Enable retries and run test_get_pronunciation_value_error. _service.enable_retries() @@ -592,7 +598,6 @@ def test_create_custom_model_value_error(self): with pytest.raises(ValueError): _service.create_custom_model(**req_copy) - def test_create_custom_model_value_error_with_retries(self): # Enable retries and run test_create_custom_model_value_error. _service.enable_retries() @@ -765,7 +770,6 @@ def test_update_custom_model_value_error(self): with pytest.raises(ValueError): _service.update_custom_model(**req_copy) - def test_update_custom_model_value_error_with_retries(self): # Enable retries and run test_update_custom_model_value_error. _service.enable_retries() @@ -842,7 +846,6 @@ def test_get_custom_model_value_error(self): with pytest.raises(ValueError): _service.get_custom_model(**req_copy) - def test_get_custom_model_value_error_with_retries(self): # Enable retries and run test_get_custom_model_value_error. _service.enable_retries() @@ -913,7 +916,6 @@ def test_delete_custom_model_value_error(self): with pytest.raises(ValueError): _service.delete_custom_model(**req_copy) - def test_delete_custom_model_value_error_with_retries(self): # Enable retries and run test_delete_custom_model_value_error. _service.enable_retries() @@ -1013,7 +1015,6 @@ def test_add_words_value_error(self): with pytest.raises(ValueError): _service.add_words(**req_copy) - def test_add_words_value_error_with_retries(self): # Enable retries and run test_add_words_value_error. _service.enable_retries() @@ -1090,7 +1091,6 @@ def test_list_words_value_error(self): with pytest.raises(ValueError): _service.list_words(**req_copy) - def test_list_words_value_error_with_retries(self): # Enable retries and run test_list_words_value_error. _service.enable_retries() @@ -1176,7 +1176,6 @@ def test_add_word_value_error(self): with pytest.raises(ValueError): _service.add_word(**req_copy) - def test_add_word_value_error_with_retries(self): # Enable retries and run test_add_word_value_error. _service.enable_retries() @@ -1257,7 +1256,6 @@ def test_get_word_value_error(self): with pytest.raises(ValueError): _service.get_word(**req_copy) - def test_get_word_value_error_with_retries(self): # Enable retries and run test_get_word_value_error. _service.enable_retries() @@ -1332,7 +1330,6 @@ def test_delete_word_value_error(self): with pytest.raises(ValueError): _service.delete_word(**req_copy) - def test_delete_word_value_error_with_retries(self): # Enable retries and run test_delete_word_value_error. _service.enable_retries() @@ -1419,7 +1416,6 @@ def test_list_custom_prompts_value_error(self): with pytest.raises(ValueError): _service.list_custom_prompts(**req_copy) - def test_list_custom_prompts_value_error_with_retries(self): # Enable retries and run test_list_custom_prompts_value_error. _service.enable_retries() @@ -1518,7 +1514,6 @@ def test_add_custom_prompt_value_error(self): with pytest.raises(ValueError): _service.add_custom_prompt(**req_copy) - def test_add_custom_prompt_value_error_with_retries(self): # Enable retries and run test_add_custom_prompt_value_error. _service.enable_retries() @@ -1599,7 +1594,6 @@ def test_get_custom_prompt_value_error(self): with pytest.raises(ValueError): _service.get_custom_prompt(**req_copy) - def test_get_custom_prompt_value_error_with_retries(self): # Enable retries and run test_get_custom_prompt_value_error. _service.enable_retries() @@ -1674,7 +1668,6 @@ def test_delete_custom_prompt_value_error(self): with pytest.raises(ValueError): _service.delete_custom_prompt(**req_copy) - def test_delete_custom_prompt_value_error_with_retries(self): # Enable retries and run test_delete_custom_prompt_value_error. _service.enable_retries() @@ -1807,7 +1800,6 @@ def test_create_speaker_model_value_error(self): with pytest.raises(ValueError): _service.create_speaker_model(**req_copy) - def test_create_speaker_model_value_error_with_retries(self): # Enable retries and run test_create_speaker_model_value_error. _service.enable_retries() @@ -1884,7 +1876,6 @@ def test_get_speaker_model_value_error(self): with pytest.raises(ValueError): _service.get_speaker_model(**req_copy) - def test_get_speaker_model_value_error_with_retries(self): # Enable retries and run test_get_speaker_model_value_error. _service.enable_retries() @@ -1955,7 +1946,6 @@ def test_delete_speaker_model_value_error(self): with pytest.raises(ValueError): _service.delete_speaker_model(**req_copy) - def test_delete_speaker_model_value_error_with_retries(self): # Enable retries and run test_delete_speaker_model_value_error. _service.enable_retries() @@ -2040,7 +2030,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries()